PowerShell — every common shell command
Object-oriented shell on Windows; cross-platform via pwsh. Uses verb-noun cmdlets.
cmd.exe vs PowerShell — they are not the same shell
cmd.exe and PowerShell both run on Windows, but they are different shells with different syntax, different pipe semantics, and almost no source-level compatibility. Knowing which one is open decides whether `dir` or `Get-ChildItem`, `%PATH%` or `$Env:Path`, `if exist file` or `if (Test-Path file)` is the right answer.
Origin & era
cmd.exeSuccessor to COMMAND.COM from MS-DOS, present on every Windows install since NT. The feature set has been frozen for decades — Microsoft no longer adds built-ins.
PowerShellDesigned from scratch in 2006 on top of .NET. PowerShell 5.1 ships with modern Windows; PowerShell 7+ (`pwsh`) is a separate cross-platform install.
What pipes carry
cmd.exeRaw text bytes. The next command parses lines itself with `find`, `findstr`, `for /f`, etc.
PowerShellTyped .NET objects with properties and methods. Downstream cmdlets read fields directly: `Get-Process | Where-Object CPU -gt 10`.
This is the deepest difference between the two shells. Most other quirks follow from text vs. objects.
Variables
cmd.exe`set NAME=value` to define. `%NAME%` to expand inside commands; `!NAME!` with delayed expansion enabled. No types — everything is an environment string.
PowerShell`$Name = value` to define. `$Name` to expand. Holds any object, with scopes (`$global:`, `$script:`, `$env:`).
Conditionals
cmd.exe`IF EXIST file (echo yes) ELSE (echo no)` — comparisons are `==`, `EQU`, `NEQ`, `LSS`, `GTR`.
PowerShell`if (Test-Path file) { "yes" } else { "no" }` — comparisons are `-eq`, `-ne`, `-lt`, `-gt`, `-match`. `==` is **not** a comparison operator.
Loops
cmd.exe`for %f in (*.log) do @echo %f` interactively, or `%%f` inside a `.bat`/`.cmd` file. `for /f` parses lines from files or command output.
PowerShell`Get-ChildItem *.log | ForEach-Object { $_.Name }` — or `foreach ($f in Get-ChildItem *.log) { ... }`. Pipeline-first.
Script files
cmd.exe`.bat` or `.cmd` — plain text, runs directly. No signing, no execution policy.
PowerShell`.ps1` — gated by execution policy. `Set-ExecutionPolicy RemoteSigned` is the usual unblock on Windows.
Cross-platform reach
cmd.exeWindows-only. Not part of WSL, not on macOS or Linux.
PowerShellPowerShell 7+ (`pwsh`) runs on Windows, macOS, and Linux. Cmdlets like `Get-ChildItem`, `Select-String`, `Invoke-WebRequest` work the same everywhere.
Unix-name commands
cmd.exeNo Unix aliases. `ls`, `cat`, `cp`, `mv`, `rm`, `grep` simply do not exist — use `dir`, `type`, `copy`, `move`, `del`, `findstr`.
PowerShell`ls`, `cat`, `cp`, `mv`, `rm`, `ps` are **aliases** for cmdlets. They accept PowerShell parameters, not Unix flags — `ls -la` errors with "parameter cannot be found".
This is the most common source of "but it worked on Linux" pain on Windows.
Comments
cmd.exe`REM comment` or `:: comment` (a label trick). No block-comment syntax.
PowerShell`# line comment` or `<# block comment #>`.
Quoting & escaping
cmd.exeEscape with `^` outside quotes; embed a literal quote with `""`. Limited interpolation — only `%VAR%` and `!VAR!`.
PowerShellEscape with backtick `` ` ``. Double quotes interpolate `$var` and `$()`; single quotes are literal.
All seeded commands in PowerShell (227)
Files (48)
- add-contentPowerShell's append-to-file cmdlet — the equivalent of bash `>>` redirection that adds content to the end of an existing file.
Add-Content -Path file.txt -Value "hello" - basenameStrip the directory part of a path, leaving only the final filename component.
Split-Path -Leaf "C:\Windows\System32\drivers\etc\hosts" - catPrint file contents to standard output.
Get-Content file.txt - command-vPOSIX way to test whether a command exists and where it resolves.
Get-Command python3 -ErrorAction SilentlyContinue - copy-itemPowerShell's copy cmdlet — the cp equivalent.
Copy-Item -Path source -Destination dest - cpCopy files and directories.
Copy-Item source dest - ddCopy and convert files at the block level — used for disk imaging, raw I/O, and filling test files.
[IO.File]::WriteAllBytes("output.bin", [byte[]]::new(1MB)) - dfReport mounted-filesystem free space and inode usage.
Get-PSDrive -PSProvider FileSystem - dirnameStrip the final filename component from a path, leaving only the directory part.
Split-Path -Parent "C:\Windows\System32\drivers\etc\hosts" - duSummarize disk usage of files and directories.
Get-ChildItem -Recurse | Measure-Object Length -Sum - fileIdentify a file by its magic bytes, not its extension.
# No native equivalent — install via `winget install file` or use Get-Content/[byte[]] checks. - findLocate files by name, size, time, or other attributes.
Get-ChildItem -Recurse -Filter *.log - get-childitemPowerShell's directory-listing cmdlet — the ls equivalent.
Get-ChildItem -Force - get-commandPowerShell's command-introspection cmdlet — the which / type / command -v equivalent that returns rich CommandInfo objects.
Get-Command jq - get-contentPowerShell's file-read cmdlet — the cat / tail equivalent.
Get-Content file.txt - get-locationPowerShell's current-directory cmdlet — the pwd equivalent that returns a structured PathInfo object.
Get-Location - lessPage through a file with backward navigation and search.
less file.txt - lnCreate a hard link or symbolic link to a file or directory.
New-Item -ItemType SymbolicLink -Path linkname -Target target - lsList directory contents.
Get-ChildItem -Force - lsblkList block devices (disks, partitions, LVM volumes, RAID arrays) as a tree showing size, mountpoint, and filesystem.
Get-Disk - md5sumPrint an MD5 hash of one or more files. Cryptographically broken — integrity-only.
Get-FileHash file.bin -Algorithm MD5 - mkdirCreate a new directory.
New-Item -ItemType Directory -Path dir - mktempCreate a uniquely-named temporary file (or directory) in a race-free way.
New-TemporaryFile - moreView a file one screen at a time (basic pager).
more file.txt - mountAttach a filesystem (disk, image, network share) to a directory in the tree so its contents become accessible.
New-PSDrive -Name D -PSProvider FileSystem -Root \\server\share -Persist - move-itemPowerShell's move/rename cmdlet — the mv equivalent.
Move-Item -Path source -Destination dest - mvMove or rename files and directories.
Move-Item source dest - new-itemPowerShell's create-file/directory cmdlet — like touch + mkdir.
New-Item -ItemType File file.txt - out-filePowerShell's pipeline-to-file cmdlet — the equivalent of bash `>` redirection that writes formatted text output to a file.
command | Out-File out.txt - readlinkPrint the target of a symbolic link, or the canonical path.
(Get-Item ./symlink).Target - realpathResolve a path to its absolute, canonical form.
Resolve-Path ./symlink - remove-itemPowerShell's delete cmdlet — the rm / rmdir / del equivalent.
Remove-Item file.txt - resolve-pathPowerShell's path-canonicalize cmdlet — the realpath equivalent.
Resolve-Path file.txt - rmDelete files and directories.
Remove-Item file - set-contentPowerShell's verbatim file-writer cmdlet — the equivalent of bash `>` that overwrites a file with raw, unformatted content.
Set-Content -Path file.txt -Value "hello" - set-locationPowerShell's working-directory cmdlet — the cd equivalent that also navigates registry and other PowerShell providers.
Set-Location C:\Users - sha1sumPrint a SHA-1 hash of one or more files. Cryptographically broken — integrity-only.
Get-FileHash file.bin -Algorithm SHA1 - sha256sumPrint a SHA-256 hash of one or more files.
Get-FileHash file.bin -Algorithm SHA256 - sha512sumPrint a SHA-512 hash of one or more files — 128 hex chars, current best-practice for high-stakes integrity.
Get-FileHash file.bin -Algorithm SHA512 - shasumBSD/macOS Perl wrapper that computes SHA-1 through SHA-512 hashes of files.
Get-FileHash file.bin -Algorithm SHA256 - statPrint a file's size, mode, owner, and timestamps.
Get-Item file.txt | Format-List * - test-pathPowerShell's path-existence cmdlet — the bash [ -e ] equivalent.
Test-Path /etc/hosts - touchCreate an empty file or update its modification time if it exists.
New-Item file.txt - treePrint a directory tree showing files and subdirectories.
tree /F - typeShow how a name is interpreted — builtin, function, alias, or file.
Get-Command ls - umountDetach a previously mounted filesystem from its directory in the tree, flushing pending writes first.
Remove-PSDrive -Name D - whereisLocate the binary, source, and manual page for a command.
Get-Command ls -All | Select-Object Source, CommandType - whichLocate an executable in PATH and print its full path.
Get-Command python3
Text (46)
- awkPattern scanning and processing language for structured text.
Get-Content file | ForEach-Object { ($_ -split '\s+')[0] } - bcArbitrary-precision command-line calculator that evaluates an expression and prints the result.
2 + 2 - cmpByte-by-byte comparison of two files — the binary counterpart to diff.
(Get-FileHash a.bin).Hash -eq (Get-FileHash b.bin).Hash - columnFormat whitespace- or delimiter-separated input into aligned columns.
Import-Csv file.csv | Format-Table -AutoSize - commCompare two SORTED files line by line, emitting three columns: only-in-file1, only-in-file2, in-both.
Compare-Object (Get-Content file1.txt) (Get-Content file2.txt) - compare-objectPowerShell's set-difference cmdlet — the diff equivalent for comparing two collections of objects or text.
Compare-Object (Get-Content file1) (Get-Content file2) - convertfrom-jsonParse a JSON string into PowerShell objects you can pipe and filter.
Get-Content users.json | ConvertFrom-Json | ForEach-Object { $_.name } - convertto-jsonSerialise a PowerShell object graph to a JSON string.
@{name='alice'} | ConvertTo-Json - cutExtract sections (fields or characters) from each line.
Get-Content file.csv | ForEach-Object { ($_ -split ',')[0] } - diffCompare two files or directories line-by-line and report the differences.
Compare-Object (Get-Content file1.txt) (Get-Content file2.txt) - echoPrint arguments to standard output, separated by spaces, followed by a newline.
echo "hello world" - export-csvWrite PowerShell objects to a CSV file with a header row.
$users | Export-Csv -Path users.csv -NoTypeInformation - grepSearch file contents for a pattern.
Select-String -Pattern "pattern" -Path *.txt - group-objectPowerShell's grouping cmdlet — the `sort | uniq -c` equivalent that buckets items by a property and returns counts plus the underlying groups.
Get-Content file.txt | Group-Object - headOutput the first lines of a file.
Get-Content file -TotalCount 10 - hexdumpBSD-style hexadecimal dump — flexible format strings for byte-level inspection.
Format-Hex file.bin - iconvConvert text between character encodings (UTF-8, UTF-16, Latin-1, GBK, …) with optional transliteration.
$content = Get-Content input.txt -Raw -Encoding UTF8; [System.IO.File]::WriteAllText("output.txt", $content, [System.Text.Encoding]::Unicode) - import-csvRead a CSV file into PowerShell objects, inferring property names from the header row.
Import-Csv users.csv | ForEach-Object { $_.name } - jqCommand-line JSON processor — filter, transform, and build JSON from the shell.
Invoke-RestMethod https://api.example.com/users | ForEach-Object { $_.name } - measure-objectPowerShell's aggregation cmdlet — counts items and computes sum/min/max/average, similar to wc plus awk arithmetic.
Get-Content file.txt | Measure-Object -Line -Word -Character - nlNumber the lines of a file (or stdin), emitting line numbers followed by each line.
Get-Content file.txt | ForEach-Object { $i = 0 } { $i++; "{0,6}`t{1}" -f $i, $_ } - odDump file contents in octal, hexadecimal, decimal, or character form — for binary inspection.
Format-Hex file.bin - pasteMerge corresponding lines of two or more files side-by-side, tab-separated by default.
$a = Get-Content a.txt; $b = Get-Content b.txt; 0..($a.Count-1) | ForEach-Object { "$($a[$_])`t$($b[$_])" } - patchApply a unified diff to source files, transforming them in place.
git apply changes.patch - sedStream editor for filtering and transforming text.
(Get-Content file) -replace 'old', 'new' - select-objectPowerShell's projection cmdlet — picks specific properties or the first/last N objects, like cut + head + tail combined.
Get-Process | Select-Object Name, CPU -First 10 - select-stringPowerShell's pattern-search cmdlet — the grep equivalent.
Select-String -Pattern "pattern" -Path file.txt - seqGenerate an arithmetic sequence of numbers (1, 2, 3, … N) — one per line by default.
1..10 - sortSort lines of text.
Get-Content file | Sort-Object - sort-objectPowerShell's sort cmdlet — sorts pipeline objects by one or more properties.
Get-Process | Sort-Object CPU -Descending - splitSplit a large file into smaller chunks by line count, byte size, or chunk count.
$lines = Get-Content huge.txt; for ($i=0; $i -lt $lines.Count; $i += 1000) { $lines[$i..($i+999)] | Set-Content "chunk_$([Math]::Floor($i/1000)).txt" } - stringsExtract printable ASCII (and optionally UTF-16) sequences from binary files.
Select-String -Path file.bin -Pattern "[\x20-\x7e]{4,}" -AllMatches | ForEach-Object { $_.Matches.Value } - tacConcatenate and print files in reverse line order.
$l = Get-Content file.txt; $l[($l.Count-1)..0] - tailOutput the last lines of a file.
Get-Content file -Tail 10 - teeRead stdin and write to both stdout and one or more files at once.
command | Tee-Object -FilePath output.txt - trTranslate or delete characters from input.
Get-Content file | ForEach-Object { $_.ToUpper() } - uniqFilter adjacent duplicate lines.
Get-Content file | Sort-Object -Unique - wcCount lines, words, or bytes.
(Get-Content file).Count - where-objectPowerShell's pipeline filter cmdlet — the awk/grep equivalent for filtering objects by property.
Get-Process | Where-Object { $_.CPU -gt 100 } - write-hostPowerShell's host-UI writer — the coloured-banner echo that bypasses the pipeline and prints directly to the terminal.
Write-Host "hello" -ForegroundColor Red - write-outputPowerShell's pipeline-emitter cmdlet — the echo equivalent that sends objects, not just text, down the pipeline.
Write-Output "hello" - xargsBuild and execute command lines from standard input.
Get-ChildItem -Recurse -Filter *.tmp | ForEach-Object { Remove-Item $_.FullName } - xmllintParse, validate, and query XML documents on the command line — from the libxml2 project. XPath queries, DTD/XSD validation, pretty-printing, and XInclude resolution.
Select-Xml -Path books.xml -XPath "//book[@id='1']/title" | ForEach-Object { $_.Node.InnerText } - xxdHexadecimal dump utility — show file contents as hex bytes plus ASCII gutter.
Format-Hex file.bin - yesEmit a string (default "y") repeatedly until killed — used to auto-confirm interactive prompts.
& { while ($true) { "y" } } | pip uninstall some-package - yqQuery, transform, and edit YAML, JSON, TOML, and XML on the command line — the jq-shaped tool for non-JSON config formats. TWO competing implementations: mikefarah/yq (Go, jq-syntax-compatible) and kislyuk/yq (Python, jq-wrapper).
Install-Module powershell-yaml; ConvertFrom-Yaml (Get-Content deployment.yaml -Raw) | Select-Object -ExpandProperty spec | Select-Object -ExpandProperty replicas
Shell (57)
- aliasCreate a shortcut name for a longer command line.
Set-Alias ll Get-ChildItem - aptInstall, upgrade, and remove packages on Debian / Ubuntu / Mint via the APT package manager — the canonical "install software" command for Debian-family Linux.
winget install nginx - bang-bangHistory expansion `!!` — repeat the previous command.
Invoke-History - bang-dollarHistory expansion `!$` — last argument of the previous command.
((Get-History -Count 1).CommandLine -split ' ')[-1] - breakExit the innermost (or N-th enclosing) loop.
foreach ($i in 1..3) { if ($i -eq 2) { break }; $i } - brewInstall, upgrade, and remove packages on macOS (and Linux) via Homebrew — the de-facto macOS package manager, also installable as Linuxbrew on Debian / RHEL.
winget install BurntSushi.ripgrep.MSVC - clear-hostPowerShell's terminal-clearing cmdlet — the clear / cls equivalent that wipes the visible scrollback.
Clear-Host - continueSkip to the next iteration of the innermost (or N-th enclosing) loop.
foreach ($i in 1..3) { if ($i -eq 2) { continue }; $i } - datePrint the current date and time, or format an arbitrary date — the surface you reach for to timestamp logs, name backup files, or compute "now minus N days".
Get-Date - declareDeclare a variable, an array, or set variable attributes.
[int]$count = 0 - dialogGenerate ncurses-style TUI widgets (menus, prompts, checkboxes, gauges, password fields) from shell scripts — capture user input as exit-code + stderr text.
$name = Read-Host "Enter your name" - double-bracket[[ ]] extended test in bash/zsh with regex and patterns.
if ("$name" -eq "alice") { ... } - envPrint the current environment variables — every `NAME=value` pair exported into the running process, plus the gateway for running a command with a modified environment.
Get-ChildItem Env: - evalParse and execute a string as if it were a shell command.
Invoke-Expression $cmd - execReplace the current shell with another program.
& python script.py - exitTerminate the current shell or script with an optional exit status.
exit 0 - expectAutomate interactive command-line programs — Tcl-based scripting tool that "expects" patterns in a program's output and "sends" responses, like a programmable user.
# pwsh has no native expect. Use WSL or install Cygwin: wsl expect -c "spawn ssh user@host; ..." - exportSet an environment variable and mark it for export to child processes.
$env:NAME = "value" - exprEvaluate an expression (POSIX arithmetic / string ops).
2 + 3 - fcEdit and re-run the previous command in $EDITOR.
Get-History | Out-GridView -PassThru | Invoke-History - foreach-objectPowerShell's pipeline-loop cmdlet — the xargs / while-read equivalent for running a block per object.
Get-Process | ForEach-Object { $_.Name } - functionDefine a reusable named function in a shell script.
function Greet { param($name) "hi $name" } - get-datePowerShell's current-time and date-arithmetic cmdlet.
Get-Date - get-helpPowerShell's documentation cmdlet — the man / info equivalent that pulls help text for cmdlets, functions, and conceptual topics.
Get-Help Get-Process - get-memberPowerShell object introspection — list properties, methods, and events on an object.
$obj | Get-Member - getoptsParse short option flags inside a shell script.
param([switch]$a, [string]$b, [switch]$c) - gpgOpenPGP encryption, signing, and key management — GnuPG.
gpg.exe --encrypt --recipient RECIPIENT-KEY-ID file - groupsList the groups a user belongs to — controlling which files, devices, and capabilities the user can access via group permissions.
whoami /groups - historyShow previously run commands from the shell history.
Get-History - idPrint the current user's UID, GID, and group memberships.
[System.Security.Principal.WindowsIdentity]::GetCurrent() - invoke-expressionPowerShell's runtime string-evaluator cmdlet — the `eval` equivalent that parses and executes a string as code. Powerful and dangerous.
Invoke-Expression $cmdString - letBash/zsh arithmetic-evaluation builtin — assign integer expressions to variables.
$x = $y * 2 - manDisplay the manual page for a command — the canonical authoritative documentation that ships with the binary, before tutorials or Stack Overflow answers.
Get-Help Get-ChildItem -Full - passwdChange a user account password — set, expire, lock, or unlock.
Set-LocalUser -Name alice -Password (Read-Host -AsSecureString) - pipInstall, upgrade, and remove Python packages from PyPI — Python's standard package manager, identical CLI across Linux, macOS, and Windows.
pip install requests - printenvPrint the value of a specific environment variable (or all of them) — `env` without the subprocess-launching machinery, optimised for scripts that just want to read.
$env:PATH - printfPrint formatted text using C-style format specifiers like %s and %d.
"{0}`n" -f "hello" - readRead a line of input into one or more shell variables interactively.
$name = Read-Host -Prompt "Name" - read-hostPowerShell interactive prompt — read a string (or SecureString) from the user.
$name = Read-Host -Prompt "Enter name" - returnExit a shell function with a numeric status code.
return 1 - rpmInstall, query, verify, and uninstall individual `.rpm` package files on RHEL / CentOS / Fedora / SUSE — the low-level package backend underneath yum/dnf/zypper.
Get-Package - setToggle shell options like errexit/xtrace and set positional parameters.
Set-StrictMode -Version Latest - sleepPause execution for a number of seconds.
Start-Sleep -Seconds 5 - sourceLoad a script into the current shell so its definitions persist.
. .\script.ps1 - testEvaluate a conditional — file tests, string and number comparisons.
Test-Path /etc/hosts - timeMeasure how long a command takes to run.
Measure-Command { some_command } - timesShow accumulated CPU time used by the shell and its children.
(Get-Process -Id $PID).CPU - tmuxTerminal multiplexer — keep multiple shell sessions alive in one terminal, detach and reattach across SSH disconnects, and split panes for side-by-side work.
Start-Job -Name work -ScriptBlock { ... } - trapRun a handler when the shell receives a signal or exits.
try { script } finally { cleanup } - typesetDeclare a variable or set its attributes (zsh canonical name).
[int]$count = 0 - ulimitRead or set the shell process's resource limits (open files, stack, memory, …).
(Get-Process -Id $PID).MaxWorkingSet = 1GB - unaliasRemove an alias previously defined with alias.
Remove-Item Alias:ll - unsetRemove a shell variable or function from the current environment.
Remove-Variable FOO - waitPause until background jobs or processes finish.
Wait-Process -Name notepad - whoShow who is currently logged in — listing each active session with username, terminal, login time, and remote host.
quser - whoamiPrint the effective username of the current process — the identity files would be created as and that permissions checks resolve against.
$env:USERNAME - yumInstall, upgrade, and remove packages on RHEL / CentOS / Fedora / Amazon Linux via YUM (Yellowdog Updater, Modified) — the RPM-family package manager, succeeded by `dnf` in RHEL 8+.
winget install nginx
Navigation (7)
- cdChange the current working directory.
Set-Location /path/to/dir - dirsList the directory stack built up by pushd and popd.
Get-Location -Stack - pop-locationPowerShell's popd — return to the directory most recently pushed.
Pop-Location - popdPop the top directory off the directory stack and cd into it.
Pop-Location - push-locationPowerShell's pushd — save the current directory on a stack, then cd.
Push-Location /etc - pushdPush the current directory onto a stack and cd into a new one.
Push-Location /tmp - pwdPrint the current working directory.
Get-Location
Process (26)
- bgResume a stopped (Ctrl+Z’d) job and run it in the background.
Start-Job { command } - crontabSchedule recurring commands on Unix — the user's `crontab` file lists `<minute> <hour> <day> <month> <weekday> <command>` entries that cron runs in the background.
Register-ScheduledTask -TaskName Backup -Trigger (New-ScheduledTaskTrigger -Daily -At 3am) -Action (New-ScheduledTaskAction -Execute pwsh -Argument "-File C:\backup.ps1") - disownRemove a background job from the shell's job table so it survives shell exit.
Start-Process .\long-job.exe -NoNewWindow - dmesgPrint the kernel ring buffer — boot-time hardware probes, device hot-plug events, OOM killer activity, and other kernel-level diagnostics that don't go to userspace logs.
Get-WinEvent -LogName System -ProviderName "Microsoft-Windows-Kernel-General" -MaxEvents 50 - fgBring a background or stopped job to the foreground.
Receive-Job -Wait -Id 1 - freeDisplay the system's used and free memory — total RAM, used, free, shared, buffer/cache, and swap, for quick "is this box memory-pressured" checks.
Get-CimInstance Win32_OperatingSystem | Select-Object FreePhysicalMemory, TotalVisibleMemorySize - get-processPowerShell's process-listing cmdlet — the ps equivalent.
Get-Process - get-servicePowerShell's service-listing cmdlet — like systemctl or service.
Get-Service - jobsList background and stopped jobs in the current shell session.
Get-Job - journalctlQuery the systemd journal — the central binary log database on systemd-based Linux systems where boot logs, service stdout/stderr, and kernel ring buffer all live.
Get-WinEvent -LogName System -MaxEvents 50 - killSend a signal to a process (typically to terminate it).
Stop-Process -Id <pid> - lsofList open files — including regular files, sockets, pipes, devices, and the processes holding them.
Get-Process -Id (Get-NetTCPConnection -LocalPort 8080).OwningProcess - niceLaunch a process with an adjusted scheduling priority (niceness).
Start-Process -FilePath .\long-running-job.exe -Priority BelowNormal - nohupRun a command immune to SIGHUP so it survives the terminal closing.
Start-Process -WindowStyle Hidden cmd-or-exe - pgrepFind PIDs (and optionally command lines) of running processes by name or other attribute — the lookup half of pkill/pgrep.
Get-Process -Name firefox - pidofReturn the PID(s) of a running process by exact name — the simpler, Linux-only cousin of pgrep.
(Get-Process -Name firefox -ErrorAction SilentlyContinue).Id - pkillKill processes by name (or other attribute) without first looking up the PID.
Stop-Process -Name firefox - psList a snapshot of currently running processes.
Get-Process - reniceChange the scheduling priority of an already-running process.
(Get-Process -Id 1234).PriorityClass = "BelowNormal" - screenDetachable terminal multiplexer — sessions survive disconnects.
Start-Job { long-cmd } - start-processPowerShell's process-launcher cmdlet — the equivalent of background `&` / `nohup` / `Start` for spawning detached or elevated processes.
Start-Process notepad - stop-servicePowerShell's stop-service cmdlet — like systemctl stop.
Stop-Service -Name w3svc - straceTrace system calls and signals received by a running process — Linux's ptrace-based syscall debugger. The canonical "why did my program fail with no useful error" tool.
Trace-Command -Name ParameterBinding -Expression { Get-ChildItem } -PSHost - systemctlControl systemd services — start, stop, enable at boot, and inspect status — on every modern Linux distro.
Restart-Service -Name nginx - topInteractive process viewer — show running processes sorted by CPU or memory, refreshed in place.
Get-Process | Sort-Object CPU -Descending | Select-Object -First 20 - unamePrint kernel and OS identification — what kernel version, machine architecture, and OS family the script is running on, for portability branching.
[System.Environment]::OSVersion
Network (27)
- curlTransfer data from or to a server over HTTP, HTTPS, FTP, and many other protocols.
Invoke-WebRequest https://example.com - digQuery DNS records (A, AAAA, MX, TXT) with richer output than nslookup.
Resolve-DnsName example.com - ftpTransfer files over FTP — legacy plaintext protocol; prefer SFTP today.
$w = [System.Net.WebClient]::new(); $w.Credentials = [System.Net.NetworkCredential]::new('user','pass'); $w.DownloadFile('ftp://ftp.example.com/file','file') - hostSimple DNS lookup with one-line output, simpler than dig.
Resolve-DnsName example.com - ifconfigThe legacy network interface configurator — still primary on macOS/BSD, deprecated on most Linux distros but still installed.
Get-NetIPAddress | Format-Table InterfaceAlias, IPAddress - invoke-restmethodPowerShell's REST and JSON HTTP client — curl that auto-deserialises the response.
Invoke-RestMethod https://api.example.com/users/1 - invoke-webrequestPowerShell's HTTP cmdlet — the curl / wget equivalent.
Invoke-WebRequest https://example.com - ipThe modern Linux network utility (from `iproute2`) — manages addresses, links, routes, neighbours, tunnels, and namespaces.
Get-NetAdapter; Get-NetIPAddress - ncNetcat — read/write arbitrary TCP and UDP data. Used for port probes, one-shot listeners, file transfer, and quick socket debugging.
Test-NetConnection -ComputerName host -Port 80 - netstatShow network connections, listening ports, routing tables, and interface statistics.
Get-NetTCPConnection -State Listen - nslookupQuery DNS records (A, AAAA, MX, TXT, etc.) for a hostname.
Resolve-DnsName example.com - pingSend ICMP echo requests to test reachability and round-trip latency.
Test-Connection example.com - rloginRemote login — DEPRECATED unencrypted predecessor to ssh.
ssh user@host - routeDisplay and manipulate the IP routing table — the rules that decide which interface and gateway each outbound packet uses.
Get-NetRoute - rshRemote shell — DEPRECATED unencrypted predecessor to ssh.
ssh user@host command - rsyncEfficient file and directory sync, transferring only changed parts.
robocopy src dest /E /Z - scpSecurely copy files between hosts over SSH.
scp local.txt user@host:/tmp/ - sftpInteractive file transfer over SSH — the secure replacement for FTP.
sftp user@host - ssSocket statistics — the modern Linux replacement for `netstat`, querying kernel sockets directly via netlink.
Get-NetTCPConnection - sshOpen a secure shell on a remote host or run a remote command.
ssh user@host - ssh-keygenGenerate, inspect, and manage SSH key pairs — the asymmetric credentials used by SSH for passwordless authentication and host verification.
ssh-keygen -t ed25519 -C "[email protected]" - telnetOpen a plaintext TCP session — legacy terminal + port-probe tool.
Test-NetConnection -ComputerName example.com -Port 25 -InformationLevel Detailed - test-connectionPowerShell's reachability-check cmdlet — the ping equivalent that returns structured objects and supports TCP port tests since pwsh 7.
Test-Connection example.com -Count 4 - tracepathTrace the network path to a destination — listing each hop and its round-trip time, without root privileges.
Test-NetConnection -ComputerName google.com -TraceRoute - traceroutePrint the route packets take to a network host — hop-by-hop, with per-hop round-trip times — by sending probes with incrementing TTL values.
Test-NetConnection google.com -TraceRoute - wgetNon-interactive network downloader for HTTP, HTTPS, and FTP.
Invoke-WebRequest https://example.com/file.zip -OutFile file.zip - whoisLook up domain registration / WHOIS records.
Invoke-RestMethod https://rdap.org/domain/example.com
Archive (7)
- 7zCreate, extract, and inspect 7-Zip archives (.7z, .zip, .tar.gz, and 30+ other formats) with strong LZMA2 compression and AES-256 encryption.
Expand-7Zip -ArchiveFileName archive.7z -TargetPath . - bzip2Compress / decompress single files using the bzip2 (BWT + Huffman) algorithm — better ratio than gzip, slower, single-threaded.
# pwsh has no bzip2 cmdlet. Install via `winget install GnuWin32.bzip2` or use 7-Zip: & "$env:ProgramFiles\7-Zip\7z.exe" a -tbzip2 file.bz2 file.txt - gzipCompress (or decompress) a single file in place using the DEFLATE algorithm.
tar -czf file.gz file - tarBundle and unbundle files into a single archive (often combined with gzip / bzip2 / xz).
tar -czf archive.tar.gz dir - unzipExtract files from a ZIP archive — the read side of `zip`, available on every Unix and (since Windows 10 1803) via the bundled bsdtar.
Expand-Archive -Path archive.zip -DestinationPath ./out - xzCompress / decompress files using the LZMA2 algorithm — best ratio of any mainstream compressor, slow at compress, fast at decompress, multi-threaded by default.
& "$env:ProgramFiles\7-Zip\7z.exe" a -txz -mx=9 file.xz file.txt - zipPackage and compress files into a ZIP archive.
Compress-Archive -Path dir -DestinationPath archive.zip
Permissions (9)
- chgrpChange the group ownership of a file or directory on Unix systems.
icacls file /grant "devs":(RX) - chmodChange file mode bits (read / write / execute permissions) on Unix files.
icacls file /grant Users:(RX) - chownChange the owner (and optionally the group) of a file or directory.
$a = Get-Acl file; $a.SetOwner([System.Security.Principal.NTAccount]"user"); Set-Acl file $a - getfaclDisplay the POSIX.1e ACL of a file or directory — the per-user / per-group grants beyond the basic owner/group/other mode bits.
(Get-Acl file.txt).Access | Format-Table IdentityReference, FileSystemRights, AccessControlType, IsInherited -AutoSize - setfaclSet or modify the POSIX.1e ACL of a file or directory — grant per-user / per-group access beyond the basic owner/group/other mode bits.
$acl = Get-Acl file.txt; $rule = New-Object Security.AccessControl.FileSystemAccessRule "alice", "FullControl", "Allow"; $acl.SetAccessRule($rule); Set-Acl file.txt $acl - suSwitch to another user's identity in the current terminal — usually for becoming root or testing as a specific user.
Start-Process pwsh -Credential alice - sudoExecute a command with another user's privileges — usually root — without logging out and back in.
Start-Process pwsh -Verb RunAs -ArgumentList "-Command", "& { apt update }" - umaskSet or display the default permission MASK for newly-created files and directories.
# Windows has NO umask — ACL inheritance from the parent directory determines new-file permissions instead. To change defaults: edit the parent dir ACL with inheritable ACEs (icacls /grant Users:(OI)(CI)(RX) /t) - usermodModify an existing user account — change username, home directory, shell, primary group, supplementary groups, lock / unlock the account, or set the expiration date.
Set-LocalUser -Name alice -Description "Updated"