Cheatsheet PowerShell
Shell de automação e scripting da Microsoft
PowerShell
26
cards encontrados
Categorias:
Versões:
Comandos Básicos
Navegação
Get-Location # pwd
Set-Location C:\ # cd
Get-ChildItem # ls / dir
Get-ChildItem -Recurse -Filter *.ps1
Mover pelo sistema.
Ajuda
Get-Help Get-Process
Get-Help Get-Process -Examples
Get-Command *service*
Get-Member -InputObject "texto"
Descobrir comandos.
Aliases comuns
ls → Get-ChildItem
cd → Set-Location
cat → Get-Content
cp → Copy-Item
mv → Move-Item
rm → Remove-Item
Atalhos familiares.
Histórico e execução
Get-History
Invoke-History 5 # re-executar #5
Start-Transcript # gravar sessão
Stop-Transcript
Histórico e logging.
Pipeline e Objetos
Pipeline
Get-Process | Where-Object {
$_.CPU -gt 100 }
Get-Service | Where-Object Status -eq
"Running" | Select-Object NameEncadear comandos com |.
Measure e Group
Get-ChildItem | Measure-Object -Property
Length -Sum -Average
Get-Process | Group-Object ProcessName |
Sort-Object Count -Descending
Estatísticas e agrupamento.
Where-Object
Get-ChildItem | Where-Object {
$_.Length -gt 1MB }
Get-Process | Where-Object {
$_.ProcessName -like "*chrome*" }Filtrar objetos.
Select e Sort
Get-Process | Sort-Object CPU -Descending |
Select-Object -First 10 Name, CPU
Get-ChildItem | Sort-Object Length |
Format-Table Name, Length
Ordenar e selecionar.
ForEach-Object
Get-ChildItem *.txt | ForEach-Object {
Write-Host $_.Name $_.Length
}
1..10 | ForEach-Object { $_ * 2 }Iterar sobre coleções.
Ficheiros e Pastas
Ler e escrever
Get-Content ficheiro.txt
Get-Content ficheiro.txt -Tail 20
Set-Content ficheiro.txt "Novo texto"
Add-Content log.txt "Linha nova"
Conteúdo de ficheiros.
Criar e copiar
New-Item -Path . -Name "pasta" -Type Dir
New-Item ficheiro.txt -ItemType File
Copy-Item a.txt b.txt
Move-Item old/ new/
Manipular itens.
Pesquisar conteúdo
Select-String -Path *.log -Pattern "erro"
Select-String -Path app.log -Pattern
"exception" -Context 2,2
# Equivale a grep
Procurar em ficheiros.
Permissões e atributos
Get-Acl ficheiro.txt
Get-Item ficheiro.txt | Select-Object
Attributes, IsReadOnly
(Get-Item f.txt).IsReadOnly = $true
Ver e alterar propriedades.
Sistema e Processos
Processos
Get-Process
Get-Process -Name chrome
Stop-Process -Name notepad -Force
Start-Process "notepad.exe"
Get-Process | Sort-Object WS -Desc |
Select -First 5
Gerir processos.
Serviços
Get-Service
Get-Service -Name "wuauserv"
Start-Service -Name "Spooler"
Stop-Service -Name "Spooler"
Restart-Service -Name "nginx"
Controlar serviços Windows.
Rede
Get-NetIPAddress
Get-NetTCPConnection -LocalPort 8080
Test-Connection google.com # ping
Test-NetConnection host -Port 443
Diagnóstico de rede.
Informação do sistema
Get-ComputerInfo
Get-CimInstance Win32_OperatingSystem
Get-Volume # discos
Get-PhysicalDisk
$env:PATH
Hardware e SO.
Scripting
Variáveis
$nome = "Ana"
$lista = @(1, 2, 3)
$hash = @{ chave = "valor"; n = 42 }
Write-Host "Olá $nome"
$hash.chave
Tipos de dados.
Try / Catch
try {
Get-Content "C:\inexistente.txt" -ErrorAction Stop
} catch {
Write-Warning "Erro: $_"
} finally {
"Concluído"
}Tratamento de erros.
Condições
if ($x -gt 10) {
"Maior"
} elseif ($x -eq 10) {
"Igual"
} else {
"Menor"
}
# -eq -ne -gt -lt -ge -leEstruturas condicionais.
Loops
foreach ($item in $lista) {
Write-Host $item
}
for ($i = 0; $i -lt 10; $i++) { $i }
while ($x -lt 100) { $x *= 2 }Iteração.
Funções
function Get-Saudacao {
param(
[string]$Nome = "Mundo",
[int]$Vezes = 1
)
1..$Vezes | ForEach-Object {
"Olá, $Nome!"
}
}Definir funções com params.
Avançado
Módulos
Get-Module -ListAvailable
Import-Module ActiveDirectory
Install-Module -Name Posh-SSH
Find-Module -Name *azure*
Gerir módulos.
PowerShell Remoting
Enter-PSSession -ComputerName Server01
Invoke-Command -ComputerName Server01 {
Get-Process | Select -First 5
}
Enable-PSRemoting -Force
Executar remotamente.
WMI / CIM
Get-CimInstance Win32_BIOS
Get-CimInstance Win32_LogicalDisk |
Select DeviceID, @{N="GB Free";
E={[math]::Round($_.FreeSpace/1GB,1)}}
Consultar hardware/SO.
Agendar tarefas
$action = New-ScheduledTaskAction -Execute
"powershell.exe" -Argument "-File C:\script.ps1"
$trigger = New-ScheduledTaskTrigger -Daily -At 8am
Register-ScheduledTask -TaskName "Backup"
-Action $action -Trigger $trigger
Task Scheduler via PS.