Básico
Comandos e Ajuda
Get-Help Get-Process # show help for cmdlet Get-Help Get-Process -Online # open online docs Get-Command *service* # find commands by name Get-Alias ls # show alias target
Aliases Comuns
ls → Get-ChildItemListar arquivos e diretórios
cd → Set-LocationMudar diretório
cp → Copy-ItemCopiar arquivo ou diretório
mv → Move-ItemMover ou renomear
rm → Remove-ItemExcluir arquivo ou diretório
cat → Get-ContentLer conteúdo de arquivo
echo → Write-OutputImprimir no pipeline
cls → Clear-HostLimpar console
Variáveis
Noções Básicas de Variáveis
$name = "Alice" # string $count = 42 # integer $pi = 3.14 # double $list = @(1, 2, 3) # array $hash = @{a=1; b=2} # hashtable
Variáveis Automáticas
$_Objeto atual no pipeline
$PSVersionTableInformações de versão do PowerShell
$HOMEDiretório pessoal do usuário
$PWDDiretório atual
$nullValor nulo
$true / $falseConstantes booleanas
$ErrorArray de erros recentes
$LASTEXITCODECódigo de saída do último comando nativo
Variáveis de Ambiente
$env:PATH # read env var $env:MY_VAR = "value" # set env var Get-ChildItem Env: # list all env vars
Operadores
Operadores de Comparação
-eq -neIgual / diferente
-gt -ltMaior / menor que
-ge -leMaior/menor ou igual
-like -notlikeCorrespondência com curinga (*, ?)
-match -notmatchCorrespondência com regex
-containsColeção contém valor
-in -notinValor está na coleção
Operadores Lógicos e Outros
-and -or -notOperadores lógicos
!NOT lógico (alias)
-replaceSubstituição regex: 'hi' -replace 'h','b'
-split -joinDividir / juntar strings
..Intervalo: 1..5 → 1,2,3,4,5
?:Ternário (v7+): $x ? 'yes' : 'no'
Controle de Fluxo
if / elseif / else
if ($age -ge 18) { "Adult" } elseif ($age -ge 13) { "Teen" } else { "Child" }
switch
switch ($color) { "red" { "Stop" } "green" { "Go" } default { "Unknown" } }
Laços
foreach ($item in $list) { $item } for ($i=0; $i -lt 5; $i++) { $i } while ($x -lt 10) { $x++ } 1..5 | ForEach-Object { $_ * 2 }
Funções
Definindo Funções
function Get-Greeting { param([string]$Name = "World") "Hello, $Name!" } Get-Greeting -Name "Alice"
Parâmetros Avançados
function Copy-SafeFile { [CmdletBinding()] param( [Parameter(Mandatory)][string]$Path, [Parameter(Mandatory)][string]$Dest ) Copy-Item $Path $Dest -WhatIf:$WhatIfPreference }
Objetos e Pipeline
Noções Básicas de Pipeline
Get-Process | Sort-Object CPU -Desc | Select-Object -First 5 Get-Service | Where-Object Status -eq "Running" Get-ChildItem | Measure-Object -Property Length -Sum
Cmdlets Principais de Pipeline
Where-ObjectFiltrar objetos: | Where {$_.CPU -gt 10}
Select-ObjectEscolher propriedades: | Select Name, CPU
Sort-ObjectOrdenar: | Sort CPU -Desc
ForEach-ObjectTransformar cada: | ForEach {$_.Name}
Measure-ObjectContar, somar, média, mínimo, máximo
Group-ObjectAgrupar por valor de propriedade
Format-TableExibir como tabela: | ft -Auto
Export-CsvExportar para CSV: | Export-Csv out.csv
Arquivos
Operações com Arquivos
Get-Content log.txt # read file Set-Content out.txt "hello" # write (overwrite) Add-Content out.txt "more" # append Get-Content log.txt | Select-String "error" # grep
Cmdlets de Caminho e Arquivo
Test-Path $pathVerificar se arquivo/diretório existe
New-Item -Type FileCriar arquivo
New-Item -Type DirectoryCriar diretório
Resolve-PathObter caminho absoluto
Join-PathCombinar segmentos de caminho
Split-PathObter pai ou folha
Get-ItemPropertyAtributos e metadados do arquivo
Remove-Item -RecurseExcluir diretório recursivamente
Strings
Noções Básicas de Strings
"Hello, $name" # interpolation (double quotes) 'Hello, $name' # literal (single quotes) "Length: $($list.Count)" # expression in string @" Multi-line here-string with $name "@
Métodos de String
.ToUpper() / .ToLower()Mudar capitalização
.Trim()Remover espaços no início/fim
.Split(',')Dividir em array
.Replace('a','b')Substituir substring
.StartsWith() / .EndsWith()Verificar prefixo / sufixo
.Substring(0,5)Extrair substring
.Contains('text')Verificar se contém
-f operator'{0} is {1}' -f 'sky','blue'
Módulos
Gerenciamento de Módulos
Get-Module -ListAvailable # installed modules Find-Module -Name Az* # search gallery Install-Module -Name Pester # install from gallery Import-Module ActiveDirectory # load module
Comandos de Módulo
Get-ModuleListar módulos carregados
Import-ModuleCarregar módulo na sessão
Remove-ModuleDescarregar módulo da sessão
Update-ModuleAtualizar módulo instalado
Get-Command -Module XListar comandos no módulo
$env:PSModulePathCaminhos de busca de módulos
Padrões Comuns
Tratamento de Erros
try { Get-Item "C:\missing" -ErrorAction Stop } catch { "Error: $_" } finally { "Cleanup here" }
Política de Execução e Comunicação Remota
Get-ExecutionPolicyExibir política de script atual
Set-ExecutionPolicy RemoteSignedPermitir scripts locais
Enter-PSSession -Computer SRV1Sessão remota interativa
Invoke-Command -Computer SRV1 -Script {}Executar bloco de script remotamente
Start-Job { long-task }Executar tarefa em segundo plano
Receive-Job -Id 1Obter saída de tarefa em segundo plano