Basics
Two PowerShells
Section titled “Two PowerShells”| Windows PowerShell | PowerShell 7 | |
|---|---|---|
| Program | powershell.exe |
pwsh.exe |
| Version | 5.1 (frozen, ships with Windows) | 7.x (current, cross-platform) |
| Install | Already there | winget install --id Microsoft.PowerShell -e |
Everything in this section works in both unless noted. Check yours with:
$PSVersionTable.PSVersionCmdlets and help
Section titled “Cmdlets and help”Commands follow a Verb-Noun pattern: Get-Process, Stop-Service, New-Item…
Get-Command *service* # find commands by nameGet-Help Get-ChildItem -Examples # usage examplesGet-Help Get-ChildItem -Online # open the docs in the browserGet-Alias ls # what an alias really runsThe pipeline passes objects, not text
Section titled “The pipeline passes objects, not text”Get-Process | Where-Object CPU -gt 100 | Sort-Object CPU -Descending | Select-Object -First 5 Name, Id, CPUWhere-Objectfilters,Sort-Objectsorts,Select-Objectpicks properties or the first N items.Get-Membershows which properties and methods an object has:Get-Process | Get-Member.- A line ending in
|continues on the next line. Elsewhere, the line-continuation character is the backtick`.
Output formats:
Get-Process | Format-Table Name, Id, CPU -AutoSizeGet-Process | Export-Csv processes.csv -NoTypeInformationGet-Process | Select-Object Name, Id | ConvertTo-JsonFrom Unix to PowerShell
Section titled “From Unix to PowerShell”| Unix | PowerShell | Alias |
|---|---|---|
ls |
Get-ChildItem |
ls, dir, gci |
cd |
Set-Location |
cd |
pwd |
Get-Location |
pwd |
cat |
Get-Content |
cat, type |
tail -f |
Get-Content -Tail 20 -Wait |
|
grep |
Select-String |
sls |
cp, mv, rm |
Copy-Item, Move-Item, Remove-Item |
cp, mv, rm |
which |
Get-Command |
gcm |
ps, kill |
Get-Process, Stop-Process |
ps, kill |
df |
Get-PSDrive, Get-Volume |
|
free |
Get-CimInstance Win32_OperatingSystem |
|
env |
Get-ChildItem Env: |
The aliases accept PowerShell parameters, not Unix ones: ls -la fails, ls -Force works.
Variables and environment
Section titled “Variables and environment”$name = "dumdocentdiscunt"$env:PATH -split ';' # the PATH, one folder per line$env:MY_VAR = "value" # only for this session$HOME # your user folderRunning scripts
Section titled “Running scripts”If a .ps1 script refuses to run because of the execution policy:
Get-ExecutionPolicy -ListSet-ExecutionPolicy -Scope CurrentUser RemoteSignedYour profile, a script that runs every time PowerShell starts, lives at $PROFILE. Create and open it with:
if (-not (Test-Path $PROFILE)) { New-Item -ItemType File -Path $PROFILE -Force }notepad $PROFILE