PowerShell Cheat Sheet
Cmdlet, pipeline di oggetti e one-liner
Navigazione
Elenca file e directory. Alias ls, gci, dir. -Recurse percorre tutto, -Force include i nascosti.
Get-ChildItem Get-ChildItem -Recurse -Filter *.ts Get-ChildItem -Force gci -Directory
Cambia la directory corrente. Alias cd. Supporta - per la precedente e ~ per la home.
Set-Location s:\MaisTools cd ~ cd ..
Mostra il percorso corrente. Alias pwd.
Get-Location pwd
Verifica se un percorso esiste. Restituisce $true o $false.
Test-Path .\file.txt
Test-Path .\src -PathType Container
if (Test-Path .\dir) { 'existe' }Salva la directory corrente in uno stack (Push) e ci ritorna dopo (Pop). Utile negli script.
Push-Location C:\Temp # ...trabalho aqui... Pop-Location
Risolve un percorso relativo in assoluto, o l'inverso con -Relative.
Resolve-Path .\src Resolve-Path -Relative C:\Temp\file.txt
File
Crea file, directory o symlink. -ItemType definisce il tipo. -Force su file esistente lo tronca.
New-Item -ItemType File novo.txt New-Item -ItemType Directory -Force pasta\sub New-Item -ItemType SymbolicLink -Path link -Target target
Copia file o directory. -Recurse per gli alberi, -Force sovrascrive la destinazione.
Copy-Item a.txt b.txt Copy-Item -Recurse src\ dest\ Copy-Item *.log -Destination archive\
Sposta o rinomina file e directory.
Move-Item old.txt new.txt Move-Item *.log archive\
Elimina file o directory. -Recurse -Force elimina senza confermare (pericoloso).
Remove-Item file.txt Remove-Item -Recurse -Force node_modules Remove-Item *.tmp
Rinomina file. Accetta ScriptBlock in -NewName per rinominare in massa.
Rename-Item old.txt new.txt
Get-ChildItem *.txt | Rename-Item -NewName { $_.Name -replace '\.txt$','.md' }Ottiene informazioni di un elemento (Length, LastWriteTime, ecc). Non legge il contenuto, solo i metadati.
Get-Item .\file.txt (Get-Item file.txt).Length Get-Item file.txt | Select-Object Name, Length, LastWriteTime
Contenuto
Legge il contenuto di un file. -TotalCount come head, -Tail come tail, -Wait segue come tail -f.
Get-Content file.txt Get-Content file.txt -TotalCount 10 Get-Content file.txt -Tail 20 Get-Content app.log -Wait -Tail 100
Scrive contenuto in un file, sovrascrivendolo. -Encoding utf8 evita il default UTF-16 con BOM in PS 5.1.
Set-Content out.txt 'linha' 'a','b','c' | Set-Content lista.txt -Encoding utf8
Aggiunge contenuto a un file esistente. Equivalente a >> in bash.
Add-Content log.txt 'nova entrada' Get-Date | Add-Content log.txt
Reindirizza output a un file. -Append aggiunge, -Encoding controlla la codifica.
Get-Process | Out-File processes.txt Get-Service | Out-File -Append -Encoding utf8 services.log
Svuota il contenuto di un file senza eliminarlo.
Clear-Content log.txt Clear-Content *.tmp
Pipeline
Filtra oggetti nella pipeline per condizione. Alias ? e where. Supporta sintassi corta Proprietà -op Valore.
Get-Process | Where-Object { $_.CPU -gt 10 }
Get-Service | Where-Object Status -eq Running
gci | ? { $_.Length -gt 1MB }Ordina oggetti per proprietà. -Descending inverte, -Unique rimuove duplicati.
Get-Process | Sort-Object CPU -Descending Get-ChildItem | Sort-Object Length -Descending 'b','a','c' | Sort-Object
Seleziona N oggetti dalla pipeline o proprietà di ciascun oggetto. -ExpandProperty estrae il valore.
Get-Process | Select-Object -First 5 Get-Process | Select-Object Name, CPU, WS Get-Service | Select-Object -ExpandProperty Name
Itera la pipeline applicando un blocco a ogni oggetto. Alias % e foreach. -Parallel in parallelo (PS 7+).
Get-ChildItem | ForEach-Object { $_.Name.ToUpper() }
1..5 | %{ $_ * 2 }
$urls | ForEach-Object -Parallel { Invoke-WebRequest $_ }Conta, somma, media, massimo o minimo di una collezione. -Line, -Word, -Character per il testo.
Get-Process | Measure-Object -Property WS -Sum -Average Get-Content file.txt | Measure-Object -Line Get-ChildItem | Measure-Object
Raggruppa oggetti per proprietà. Utile per contare occorrenze o costruire dizionari con -AsHashTable.
Get-Process | Group-Object ProcessName Get-ChildItem | Group-Object Extension -NoElement
Ricerca
Cerca pattern in stringhe o file. Equivalente di grep. -Pattern accetta regex, -SimpleMatch lo disattiva.
Select-String 'TODO' *.ts Select-String -Path src\*.ts -Pattern 'error' -CaseSensitive Get-ChildItem -Recurse | Select-String 'API_KEY'
Mostra cmdlet disponibili con filtri per nome, modulo o tipo. (Get-Command npm).Source restituisce il percorso.
Get-Command npm Get-Command *process* (Get-Command npm).Source Get-Command -Module Microsoft.PowerShell.Utility
Mostra proprietà e metodi di un oggetto. Indispensabile per scoprire cosa si può fare con un tipo.
Get-Process | Get-Member (Get-Date) | Get-Member -MemberType Method 'abc' | Get-Member
Mostra l'aiuto di cmdlet o argomenti about_*. -Examples mostra esempi, -Online apre la versione web.
Get-Help Get-ChildItem Get-Help Get-Process -Examples Get-Help about_Variables Get-Help Set-Content -Online
Variabili
Le variabili iniziano con $ e non richiedono dichiarazione. Supportano array (@()) e hashtable (@{}).
$nome = 'Bruno'
$idade = 30
$lista = @(1, 2, 3)
$hash = @{ a = 1; b = 2 }Legge e definisce variabili d'ambiente. Get-ChildItem env: le elenca tutte. La modifica vale solo nella sessione corrente.
$env:PATH $env:USERPROFILE $env:DEBUG = 'true' Get-ChildItem env:
Valore nullo. Nei confronti metti $null a sinistra ($null -eq $x) per evitare sorprese con gli array.
if ($null -eq $var) { 'vazio' }
$lista = @($null, 1, 2)
[string]::IsNullOrEmpty($x)Conversione di tipo con [tipo]. Funziona per int, string, datetime, array tipizzati, regex.
[int]'42' [datetime]'2026-01-15' [int[]]$nums = 1,2,3 [regex]::Escape($pattern)
Definisce l'ambito di una variabile: global (intera sessione), script (questo file) o local (questa funzione).
$global:config = @{}
$script:contador = 0
function f { $local:tmp = 1 }Stringhe
Le virgolette doppie espandono $var e $(expr). Quelle singole sono letterali e non espandono nulla.
$nome = "Bruno" "Olá $nome" "Caminho: $($obj.Property)" 'literal $nome' # sem expansão
Stringhe multilinea (here-strings). @"..."@ espande variabili, @'...'@ è letterale. La chiusura deve stare in colonna 0.
@" linha 1 com $nome linha 2 "@ @' literal $nome '@
Operatore di formattazione tipo printf. Supporta numeri, date e allineamento ({0,5:N2}).
'{0} tem {1} anos' -f $nome, $idade
'{0:N2}' -f 1234.5678 # 1,234.57
'{0:yyyy-MM-dd}' -f (Get-Date)Operazioni sulle stringhe: -replace usa regex, -split divide in array, -join unisce un array in stringa.
'abc123' -replace '\d', 'X'
'a,b,c' -split ','
@('a','b','c') -join ', 'Controllo
Struttura condizionale. Usa operatori PowerShell (-eq, -lt) invece di == o <.
if (Test-Path .\file) {
'existe'
} elseif ($x -gt 0) {
'positivo'
} else {
'outro'
}Alternativa all'if concatenato. -Regex e -Wildcard attivano pattern, -File legge righe da un file.
switch ($x) {
1 { 'um' }
2 { 'dois' }
default { 'outro' }
}
switch -Regex ($texto) {
'^\d+$' { 'número' }
}Cicli su collezioni (foreach), con contatore (for), finché condizione (while), o almeno una volta (do/while).
foreach ($f in Get-ChildItem) { $f.Name }
for ($i = 0; $i -lt 5; $i++) { $i }
while ($cond) { ... }
do { ... } while ($cond)Cattura di errori. Per catturare errori non terminanti usa -ErrorAction Stop sul cmdlet.
try {
Cmdlet -ErrorAction Stop
} catch [System.IO.IOException] {
Write-Error "IO: $_"
} catch {
Write-Error $_
} finally {
Cleanup
}break esce dal ciclo, continue salta all'iterazione successiva, return esce dalla funzione.
foreach ($x in 1..10) {
if ($x -eq 5) { break }
if ($x % 2 -eq 0) { continue }
$x
}Operatori
Operatori di confronto. Non esiste == in PowerShell, usa sempre -eq, -ne, -lt, -gt, -le, -ge.
$x -eq 5 # igual $x -ne 5 # diferente $x -lt 10 # menor $x -gt 0 # maior $x -le 10 # menor ou igual $x -ge 0 # maior ou igual
Altri operatori: -like usa wildcard, -match usa regex, -contains verifica l'appartenenza in array, -in è l'inverso.
'file.txt' -like '*.txt' # wildcards 'abc123' -match '\d+' # regex @(1,2,3) -contains 2 # pertença 2 -in @(1,2,3) # pertença (invertido)
Operatori logici. -and, -or, -not, -xor. ! è alias di -not.
($x -gt 0) -and ($x -lt 10) ($a -eq 1) -or ($b -eq 2) -not (Test-Path .\file) !$cond
Processi
Elenca processi con proprietà (CPU, WS, Id, ProcessName). Senza argomenti li elenca tutti.
Get-Process Get-Process node, chrome Get-Process -Id 1234
Termina processi per nome o Id. -Force evita la conferma. Può ricevere oggetti dalla pipeline.
Stop-Process -Name node Stop-Process -Id 1234 -Force Get-Process node | Stop-Process
Avvia un programma. -Wait blocca fino al termine, -NoNewWindow esegue nella console corrente, -Verb RunAs eleva.
Start-Process notepad Start-Process npm -ArgumentList 'run','dev' Start-Process pwsh -Verb RunAs
Attende il termine di un processo. -Timeout annulla dopo N secondi.
Wait-Process -Name node Wait-Process -Id 1234 -Timeout 30
Esegue un comando o uno script. Necessario quando il percorso ha spazi o per chiamare eseguibili dinamicamente.
& 'C:\Program Files\App\app.exe' arg1 arg2
& $cmd
& { Get-Process; Get-Service }Dati
Converte JSON in oggetti PowerShell. -AsHashtable restituisce hashtable (PS 6+) invece di PSCustomObject.
Get-Content pkg.json | ConvertFrom-Json
'{"a":1}' | ConvertFrom-Json
$obj.dependenciesConverte oggetti PowerShell in JSON. -Depth controlla la profondità (default 2, spesso troppo basso).
$obj | ConvertTo-Json -Depth 10
@{a=1; b=2} | ConvertTo-Json -Compress
Get-Process | Select-Object Name,Id | ConvertTo-JsonLegge un CSV in oggetti con proprietà. -Delimiter per ; o altri, -Header se il file non ha intestazione.
Import-Csv users.csv Import-Csv data.csv -Delimiter ';' -Encoding utf8
Esporta oggetti in CSV. -NoTypeInformation rimuove la riga di tipo in alto (default in PS 6+).
Get-Process | Export-Csv processes.csv -NoTypeInformation $data | Export-Csv out.csv -Encoding utf8 -Delimiter ';'
Rete
Client HTTP completo. Restituisce la risposta come oggetto con .Content, .StatusCode, .Headers. Alias iwr.
Invoke-WebRequest https://example.com iwr https://api.example.com -OutFile data.json iwr -Uri $url -Method POST -Body $body
Client HTTP che esegue automaticamente il parse di JSON o XML in oggetti. Più usato per API REST. Alias irm.
Invoke-RestMethod https://api.github.com/users/octocat irm $url -Method POST -Body ($obj | ConvertTo-Json) -ContentType 'application/json'
Testa la connettività TCP a un host e porta. Solo Windows. Su Linux/macOS usa Test-Connection -TcpPort (PS 7+).
Test-NetConnection google.com -Port 443 Test-NetConnection -ComputerName 8.8.8.8 -TraceRoute
Equivalente a ping. -Count limita i pacchetti, -Quiet restituisce solo $true o $false.
Test-Connection google.com -Count 4 Test-Connection 8.8.8.8 -Quiet # bool
Moduli
Elenca moduli. -ListAvailable mostra tutti gli installati, non solo i caricati.
Get-Module Get-Module -ListAvailable Get-Module -Name Pester
Carica un modulo nella sessione corrente. -Force ricarica se già importato.
Import-Module Pester Import-Module .\MeuModulo.psm1 -Force
Installa moduli dalla PowerShell Gallery. -Scope CurrentUser evita di richiedere permessi admin.
Install-Module Pester -Scope CurrentUser Install-Module Az -Force -AllowClobber
Cerca moduli disponibili sulla PowerShell Gallery.
Find-Module Az* Find-Module -Tag azure
Avanzato
Esegue codice in background. Receive-Job raccoglie i risultati, -Wait blocca fino al termine.
$j = Start-Job { Get-Process }
Receive-Job $j -Wait -AutoRemoveJob
Get-Job | Remove-JobJob in background leggeri basati su thread (più rapidi di Start-Job). Incluso in PS 7+, in 5.1 installa con Install-Module ThreadJob.
$j = Start-ThreadJob { 1..10 | %{ $_ * 2 } }
$urls | ForEach-Object -Parallel { iwr $_ } -ThrottleLimit 5Misura il tempo di esecuzione di un blocco. Restituisce un TimeSpan con TotalSeconds, TotalMilliseconds, ecc.
Measure-Command { Get-ChildItem -Recurse }
(Measure-Command { ./script.ps1 }).TotalSecondsEsegue comandi su una macchina remota tramite WinRM. Supporta sessioni persistenti con -Session.
Invoke-Command -ComputerName server01 -ScriptBlock { Get-Service }
Invoke-Command -Session $s -ScriptBlock { hostname }Mette in pausa l'esecuzione per N secondi o millisecondi.
Start-Sleep -Seconds 5 Start-Sleep -Milliseconds 250
Riferimento
A differenza di bash, la pipeline di PowerShell trasporta oggetti con proprietà e metodi. Ogni cmdlet può accedere direttamente a .Length, .Name, .CPU senza fare il parse del testo.
Get-Process | Sort-Object CPU -Descending | Select-Object -First 5 # objectos fluem entre comandos com propriedades preservadas Get-ChildItem | Where-Object Length -gt 1MB # Each item retains its full type — pode aceder a .Length, .Name, etc. Get-Service | Group-Object Status | Format-Table Name, Count
La codifica predefinita è cambiata tra le versioni. Sapere quale è attiva evita BOM e caratteri rotti negli script e log condivisi con altri strumenti.
- Il default varia per cmdlet: Out-File usa UTF-16 LE con BOM, Set-Content usa Default (ANSI/Windows-1252).
- Nessuno produce UTF-8 senza -Encoding. Passa sempre -Encoding utf8 per file condivisi con strumenti Unix.
- Default: UTF-8 senza BOM.
- Comportamento allineato con l'ecosistema. In entrambi, -Encoding utf8 garantisce UTF-8.
Set-Content file.txt 'texto' -Encoding utf8
Out-File log.txt -Encoding utf8 -InputObject $data
[System.IO.File]::WriteAllText('file.txt', 'texto', [System.Text.UTF8Encoding]::new($false))PowerShell distingue errori terminanti da non terminanti. I cmdlet falliscono in silenzio per default, usa -ErrorAction Stop per forzare try/catch a catturarli.
Continue— comportamento standard, mostra l'errore e continua.Stop— lo trasforma in errore terminante (catturabile).SilentlyContinue— nasconde l'errore ma $? diventa $false.Ignore— nasconde e non registra in $Error.
$?— $true se l'ultimo comando è riuscito.$LASTEXITCODE— exit code dell'ultimo eseguibile nativo.$Error[0]— oggetto dell'ultimo errore registrato.
try {
Get-Item .\file -ErrorAction Stop
} catch [System.IO.FileNotFoundException] {
Write-Warning "ficheiro não encontrado"
} catch {
Write-Error $_.Exception.Message
}
# verificar saída de processo nativo
git status
if ($LASTEXITCODE -ne 0) { throw "git falhou" }Windows PowerShell 5.1 (powershell.exe) e PowerShell 7+ (pwsh.exe) hanno sintassi e funzionalità diverse. Questi dettagli rompono gli script passando da una versione all'altra.
A && B / A || B— Gli operatori && e || esistono solo in PS 7+. In 5.1 usa: A; if ($?) { B }$x ? a : b— L'operatore ternario ?: esiste solo in PS 7+. In 5.1 usa if/else.$x ?? y— L'operatore null-coalescing ?? esiste solo in PS 7+.ConvertFrom-Json -AsHashtable— ConvertFrom-Json -AsHashtable esiste solo da PS 6+.ForEach-Object -Parallel— ForEach-Object -Parallel esiste solo in PS 7+.
Combinazioni frequenti per automazione e amministrazione. Ciascuna risolve un compito specifico in una singola pipeline.
- 01.Trova file più grandi di 100MB ricorsivamente.
Get-ChildItem -Recurse -File | Where-Object Length -gt 100MB - 02.Elenca i 10 file più grandi nella directory corrente.
Get-ChildItem | Sort-Object Length -Descending | Select-Object -First 10 - 03.Mostra i 10 processi che consumano più memoria.
Get-Process | Sort-Object WS -Descending | Select-Object -First 10 - 04.Mostra i 10 processi che consumano più CPU.
Get-Process | Sort-Object CPU -Descending | Select-Object -First 10 - 05.Conta il numero totale di file ricorsivamente.
Get-ChildItem -Recurse -File | Measure-Object | Select-Object -ExpandProperty Count - 06.Elimina tutti i file .tmp ricorsivamente.
Get-ChildItem -Recurse -Filter *.tmp | Remove-Item - 07.Cerca TODO in tutti i file TypeScript.
Get-ChildItem -Recurse -File | Where-Object Extension -in '.ts','.tsx' | Select-String 'TODO' - 08.Ottiene l'IP pubblico esterno della macchina corrente.
(Invoke-WebRequest ifconfig.me -UseBasicParsing).Content.Trim() - 09.Elenca le porte TCP in ascolto con il processo associato.
Get-NetTCPConnection -State Listen | Select-Object LocalAddress,LocalPort,OwningProcess - 10.Segue un log in tempo reale partendo dalle ultime 100 righe.
Get-Content app.log -Wait -Tail 100 - 11.Ottiene data e ora correnti in un formato pronto per nomi di file.
Get-Date -Format 'yyyy-MM-dd_HH-mm-ss' - 12.Crea un backup zip con la data nel nome del file.
Compress-Archive -Path .\src -DestinationPath "backup-$(Get-Date -Format yyyy-MM-dd).zip" - 13.Formatta e stampa JSON espanso per la massima leggibilità.
Get-Content data.json | ConvertFrom-Json | ConvertTo-Json -Depth 10 - 14.Elenca tutte le variabili d'ambiente ordinate per nome.
Get-ChildItem env: | Sort-Object Name - 15.Elenca tutti i servizi attualmente in esecuzione.
Get-Service | Where-Object Status -eq 'Running' - 16.Verifica se una porta TCP è aperta su un host remoto.
Test-NetConnection google.com -Port 443 - 17.Mostra lo spazio libero su ogni disco del sistema.
Get-Volume | Select-Object DriveLetter, SizeRemaining, Size - 18.Mostra gli ultimi 20 comandi della cronologia della sessione.
Get-History | Select-Object -Last 20 - 19.Mostra il percorso completo di un comando (equivalente di which).
(Get-Command npm).Source - 20.Elenca i file modificati negli ultimi 7 giorni.
Get-ChildItem -Recurse | Where-Object { $_.LastWriteTime -gt (Get-Date).AddDays(-7) }