PowerShell Cheatsheet - PowerShell Command Reference
Most Windows scripting trouble comes from treating PowerShell as cmd: the pipeline carries objects, but you are concatenating text, so Where-Object and Sort-Object never get used. This table walks through basic commands, files and directories, content manipulation, pipelines and filtering, processes and services, networking and remoting, script authoring, and system administration, flagging where each command diverges from its Linux counterpart. The rule of thumb is whether output stays consumable: if Select-Object can pull a property, Where-Object can keep filtering; if you have to regex the text, you picked the wrong command. Reach for it when writing deployment or health-check scripts, bulk renaming or re-encoding files, diagnosing why a service will not start, or running one fix across dozens of machines. The boundary with bash is sharp: separators, line endings, and default encodings are all Windows-specific, and mixing shells produces results nobody can explain from the output alone.
Typical Use Case
For Windows administrators, developers and anyone automating daily tasks. The core idea is that the pipeline passes objects, not text, so each line of Get-Content output and every entry from Get-ChildItem can be filtered, projected, sorted, grouped, measured or looped over. Once that chain is natural, requests like listing the five highest memory processes into a CSV or finding the largest files under a directory collapse to a single line. Four side tracks are equally frequent: processes and services, web requests through Invoke-RestMethod, remote execution with Invoke-Command, and system information and event logs. Get-Command and Get-Help are the authoritative index.
Basic Commands 5
Get-CommandGet-Help Get-ProcessGet-MemberGet-VerbGet-AliasFile & Directory 8
Get-ChildItemSet-Location ..New-Item -ItemType Directory -Path C:\NewDirCopy-Item src.txt dst.txtMove-Item src.txt dst.txtRemove-Item file.txtRename-Item old.txt new.txtTest-Path C:\pathContent Operations 8
Get-Content file.txtSet-Content file.txt "text"Add-Content file.txt "text"Out-File output.txtExport-Csv data.csv -NoTypeInformationImport-Csv data.csvConvertTo-JsonConvertFrom-JsonPipeline & Filtering 6
Where-Object { $_.Name -eq "svchost" }Select-Object -First 10 Name,IdSort-Object Name -DescendingGroup-Object StatusMeasure-Object -Sum -AverageForEach-Object { $_ * 2 }Process & Service 9
Get-ProcessGet-Process -Name "chrome"Stop-Process -Name "notepad"Start-Process notepad.exeGet-ServiceStart-Service SpoolerStop-Service SpoolerRestart-Service SpoolerSet-Service Spooler -StartupType AutomaticNetwork & Remote 6
Test-Connection 8.8.8.8Test-NetConnection google.com -Port 443Invoke-WebRequest -Uri https://api.example.comInvoke-RestMethod -Uri https://api.example.comEnter-PSSession -ComputerName Server01Invoke-Command -ComputerName Server01 -ScriptBlock { Get-Process }Scripting 8
$name = "World"$array = 1,2,3; $array[0]$hash = @{ Name = "Tom"; Age = 30 }if ($val -gt 10) { "big" } else { "small" }switch ($val) { 1 { "one" } default { "?" } }foreach ($item in $items) { $item }function Say-Hello { param($name) "Hello $name" }try { 1/0 } catch { "error: $_" } finally { "done" }System Management 8
Get-DateSet-Date "2026-01-01"Get-WmiObject Win32_ProcessorGet-CimInstance Win32_LogicalDiskFormat-Table Name,Id -AutoSizeFormat-List Name,IdFormat-Wide Name -Column 4Get-EventLog -LogName System -Newest 10Parameter matrix
| Parameter | Effect | Example |
|---|---|---|
Get-Command | Supply the filesystem or registry path a cmdlet acts on; when omitted PowerShell uses the current location. | Get-Command |
Get-Help <Cmd> -Detailed | Walk every child directory as well, so a search is not limited to the top level. | Get-Help Get-Process -Detailed |
Get-Member | Restrict results with the provider wildcard syntax, which is far faster than piping into Where-Object. | Get-Process | Get-Member |
Get-Verb | Include hidden items and let Remove-Item delete read-only files that would otherwise raise an error. | Get-Verb |
Get-Alias | Suppress non-terminating error records so a loop over many paths does not flood the console. | Get-Alias |
Get-ChildItem | Print the operations the cmdlet would perform without actually changing anything. | Get-ChildItem -Path D:/code |
Set-Location .. | Limit Select-Object to the earliest or latest N items instead of the whole pipeline. | Set-Location .. |
New-Item -ItemType Directory | Stop Export-Csv from writing the #TYPE header row, which otherwise breaks naive CSV parsers. | New-Item -ItemType Directory -Path D:/NewDir |
Copy-Item / Move-Item | Flatten a nested object into the pipeline so its members become first-class results. | Move-Item src.txt dst.txt |
Remove-Item | Run the cmdlet against a remote machine through WinRM (implicit remoting). | Remove-Item file.txt |
Rename-Item | Automatic variable holding the directory of the running script, safer than relative paths in scheduled tasks. | Rename-Item old.txt new.txt |
Test-Path | Choose how Set-Content and Out-File write text; utf8NoBOM avoids the corruption Windows PowerShell 5.1 causes with a plain utf8. | Test-Path C:/path |
Get-Content | 读取文件内容 | Get-Content package.json |
Set-Content | 写入文件(覆盖) | Set-Content file.txt "text" |
Add-Content | 向文件末尾追加内容 | Add-Content file.txt "text" |
Out-File | 把管道输出写入文件 | Get-Process | Out-File output.txt |
Export-Csv -NoTypeInformation | 导出对象为 CSV(无类型行) | Get-Process | Export-Csv data.csv -NoTypeInformation |
Import-Csv | 从 CSV 导入为对象 | Import-Csv data.csv |
ConvertTo-Json | 对象转 JSON 字符串 | Get-Process | Select-Object -First 3 | ConvertTo-Json |
ConvertFrom-Json | JSON 字符串转对象 | $o = $json | ConvertFrom-Json |
Where-Object { $_.Name -eq "svchost" } | 按属性筛选对象 | Get-Process | Where-Object { $_.Name -eq "svchost" } |
Select-Object -First 10 Name,Id | 选属性或取前 N 条 | Get-Process | Select-Object -First 10 Name,Id |
Sort-Object Name -Descending | 按属性排序(可降序) | Get-Process | Sort-Object WS -Descending |
Group-Object Status | 按属性分组统计 | Get-Process | Group-Object Status |
Measure-Object -Sum -Average | 计算总和与平均值等统计 | Get-Process | Measure-Object WS -Sum -Average |
ForEach-Object { $_ * 2 } | 对每个对象执行操作 | 1..3 | ForEach-Object { $_ * 2 } |
Get-Process -Name "chrome" | 按名称查找进程 | Get-Process -Name "chrome" |
Stop-Process -Name | 结束指定进程 | Stop-Process -Name "notepad" |
Start-Process | 启动新进程 | Start-Process notepad.exe |
Get-Service | 列出所有 Windows 服务 | Get-Service |
Start-Service / Stop-Service / Restart-Service | 启动 / 停止 / 重启服务 | Restart-Service Spooler |
Set-Service -StartupType | 设置服务启动类型 | Set-Service Spooler -StartupType Automatic |
Test-Connection | 测试网络连通性 | Test-Connection 8.8.8.8 |
Test-NetConnection -Port | 测试端口连通性 | Test-NetConnection google.com -Port 443 |
Invoke-WebRequest | 发送 HTTP/HTTPS 请求 | Invoke-WebRequest -Uri https://api.example.com |
Invoke-RestMethod | 发送 REST 请求并自动解析响应 | Invoke-RestMethod -Uri https://api.example.com |
Enter-PSSession -ComputerName | 进入远程 PowerShell 会话 | Enter-PSSession -ComputerName Server01 |
Invoke-Command -ScriptBlock | 在远程机器上执行命令 | Invoke-Command -ComputerName Server01 -ScriptBlock { Get-Process } |
$name = "World" | 定义变量($ 前缀) | $name = "World" |
$array = 1,2,3; $array[0] | 数组定义与索引访问 | $array = 1,2,3; $array[0] |
$hash = @{ Name = "Tom" } | 哈希表定义 | $hash = @{ Name = "Tom"; Age = 30 } |
if ($val -gt 10) | 条件判断(-gt/-lt/-eq) | if ($val -gt 10) { "big" } else { "small" } |
switch ($val) { ... default { } } | 多分支判断 | switch ($val) { 1 { "one" } default { "?" } } |
foreach ($item in $items) | 遍历数组或集合 | foreach ($item in $items) { $item } |
function Say-Hello { param($name) } | 定义带参数的函数 | function Say-Hello { param($name) "Hello $name" } |
try / catch / finally | 异常处理三段式 | try { 1/0 } catch { "error: $_" } finally { "done" } |
Get-Date / Set-Date | 获取 / 设置系统日期时间 | Get-Date |
Get-WmiObject Win32_Processor | WMI 查询硬件信息 | Get-WmiObject Win32_Processor |
Get-CimInstance Win32_LogicalDisk | CIM 查询磁盘信息(推荐) | Get-CimInstance Win32_LogicalDisk |
Format-Table -AutoSize | 表格输出,自动对齐列宽 | Get-Process | Format-Table Name,Id -AutoSize |
Format-List | 列表输出,每属性一行 | Get-Process | Format-List Name,Id |
Format-Wide -Column 4 | 宽格式多列输出 | Get-ChildItem | Format-Wide Name -Column 4 |
Get-EventLog -LogName System -Newest 10 | 查看系统事件日志 | Get-EventLog -LogName System -Newest 10 |
Common pitfalls
SymptomA script writes UTF-8 text and the file opens with garbled characters or a stray leading byte.
CauseWindows PowerShell 5.1 defaults -Encoding to the system ANSI code page, while PowerShell 7 defaults to UTF-8 without BOM.
FixAlways pass -Encoding explicitly (utf8NoBOM for interop) and run the script under pwsh rather than powershell.exe.
SymptomRemove-Item reports that a file is in use, or the process keeps running after the files were deleted.
CauseAnother process holds an exclusive handle on the file; Windows refuses to unlink a locked file.
FixFind the holder with Get-Process | Where-Object { $_.Path -eq "C:\app.exe" } or handle.exe, stop it, then delete again.
SymptomAn alias such as ls or cat behaves unexpectedly, or a script written on Windows fails on a Linux agent.
Causels, cp, mv and rm are PowerShell aliases to the Get-ChildItem, Copy-Item, Move-Item and Remove-Item cmdlets; the same names are real binaries in bash.
FixWrite the full cmdlet name in any script that must run cross-platform, and avoid relying on aliases.
SymptomA foreach loop over file names breaks as soon as one path contains a space.
CauseThe path was interpolated unquoted, so PowerShell split it into separate arguments.
FixQuote or brace the variable: foreach ($f in $files) { Get-Item "$f" } and prefer -LiteralPath when a name may contain wildcard characters.
SymptomExecution policy blocks the script with a "cannot be loaded because running scripts is disabled" error.
CauseThe default Windows policy on a client machine is Restricted, which refuses any unsigned .ps1.
FixRun Set-ExecutionPolicy RemoteSigned -Scope CurrentUser, or sign the script and prefer pwsh -File script.ps1 with an explicit path.
SymptomSelect-Object silently returns fewer rows than the input, or the output stops at one object.
CauseThe cmdlet was piped into something that enumerates a single value, or Select-Object was called without -First/-Property on a differently typed object.
FixAdd -Property to name the columns and -ExpandProperty to unpack a nested object; confirm the upstream cmdlet actually produced the rows with Measure-Object.
SymptomFormatting disappears when the output is redirected to a file or a CI log.
CauseFormat-Table and Format-List are rendering cmdlets; their output is text, not objects, and only applies inside a pipeline.
FixNever pipe into a Format-* cmdlet when you need to reuse the data; select the properties with Select-Object and format only at the end.
Symptom1..3 | ForEach-Object { $_ } 输出的 $ 与预期数字不符,字符串拼接全乱了
Cause管道里每个元素类型不固定,字符串与数字混合时隐式转换会导致拼接结果诡异。
Fix在管道里先用 Select-Object 收敛出需要的单一属性,再做运算;必要时用 [int] 或 [string] 显式转换类型。
Troubleshooting
1Confirm which cmdlet a name actually resolves to
Get-Process | Select-Object -First 1 | Get-MemberCommandType tells you whether the name is an Alias, Function or Cmdlet, and Definition shows what it maps to.
2Discover the real parameters of a cmdlet instead of guessing
Get-Process | Sort-Object WS -Descending | Select-Object -First 5 Name,Id,WS | Format-Table Name,Id -AutoSizeListing parameters by name is the reliable way to confirm that -Filter, -Recurse and -LiteralPath exist on the installed version.
3Inspect every property an object carries
Get-Service Spooler | Format-List Name,Status,StartTypeGet-Member lists the real property and method names, which is how you find the field to filter on.
4Surface the underlying error record instead of the formatted message
Test-Connection 8.8.8.8; Test-NetConnection api.example.com -Port 443The full error record contains the category, the target object and the fully qualified error id.
5Measure what a pipeline produced before trusting it
Invoke-RestMethod -Uri https://api.example.com/data | ConvertTo-JsonThe Count property tells you whether a filter or a Select-Object narrowed the set more than you intended.
6导出结果到 CSV 并回读校验
Get-Process | Select-Object Name,Id | Export-Csv proc.csv -NoTypeInformation; Import-Csv proc.csv | Select-Object -First 3导出后立刻 Import-Csv 回读并取前 3 行,能同时验证表头是否干净(无类型信息行)与字段是否按预期落盘,避免带着脏表头交付数据。
7在远程机器上执行诊断命令
Invoke-Command -ComputerName Server01 -ScriptBlock { Get-Service | Select-Object -First 5 Name,Status }结果会以带远程主机前缀的形式返回,本地不改动任何状态。若需要多步交互式排查,改用 Enter-PSSession -ComputerName Server01 进入会话。
8查系统最近的异常线索
Get-EventLog -LogName System -Newest 10 | Format-List TimeGenerated,EntryType,Source,Message取最近 10 条并用 Format-List 展开完整字段,重点看 Level/EntryType 为 Error 的条目及其 Message,通常能直接指出是哪个服务或驱动出的问题。
Command Examples
Find the heaviest processes by CPU
Get-Process | Sort-Object CPU -Descending | Select-Object -First 5 Name, Id, @{N="MB";E={[math]::Round($_.WorkingSet64/1MB,1)}}管道是 PowerShell 的核心:Get-Process 产出对象,Sort-Object 排序,Select-Object 投影需要的列。MB 用计算属性换算字节。
Output
Name Id MB ---- -- ---- chrome 1452 812.4 code 2031 496.0 Teams 1876 231.7
Kill all processes by name
Get-Process node -ErrorAction SilentlyContinue | Stop-Process -Force-ErrorAction SilentlyContinue 在没有匹配进程时不报错,适合脚本里直接用。先用 Get-Process 确认列表再加 -Force。
Call a REST API with automatic JSON parsing
$r = Invoke-RestMethod -Uri https://api.github.com/users/octocat
$r.login
$r.public_reposInvoke-RestMethod 自动把 JSON 转成对象,属性用点号访问;Invoke-WebRequest 则返回原始文本需要自己 ConvertFrom-Json。
Output
octocat 8
Test port connectivity
Test-NetConnection github.com -Port 443比手工 ping 更能定位问题——ping 通只说明 ICMP 可达,这里能确认具体端口是否开放。
Output
ComputerName : github.com RemoteAddress : 140.82.121.4 RemotePort : 443 TcpTestSucceeded : True
Common Pitfalls
- Remove-Item -Recurse -Force deletes a whole tree with no prompt and bypasses the Recycle Bin — verify the path first.
- Windows PowerShell 5.1 and PowerShell 7+ differ substantially; check $PSVersionTable in cross-version scripts.
- Set-Content and Out-File default to UTF-16LE, which garbles output for other programs — specify -Encoding utf8.
- Stop-Process -Force is an immediate kill that skips saving; try without -Force first.
- Aliases are not resolved in non-interactive sessions — write full cmdlet names in scripts.
Tips
- PowerShell uses Verb-Noun naming convention, e.g. Get-Process, Stop-Service
- Use Get-Command to find available commands, Get-Help for documentation
- Pipeline passes objects not text, use Get-Member to inspect object properties
- Variables use $ prefix, e.g. $var = "hello"
- Use $profile to customize your PowerShell environment, similar to .bashrc
FAQ
Does the PowerShell pipeline pass objects or text, and why does it matter?
Objects. Get-ChildItem emits FileInfo/DirectoryInfo instances, which is why Where-Object { $_.Name -eq "svchost" } can reach straight into .Name, .Length and .LastWriteTime instead of a chopped-up text line. It also explains the absence of grep — filter on properties, not on regex patterns. To discover what a command actually gives you, run Get-Member; call ToString() or Out-File explicitly when you do need text.
How do I find a process by name and kill it with Get-Process and Stop-Process?
List first with Get-Process -Name "chrome" — there may be several instances — and confirm which PIDs you actually want. Then stop them via Stop-Process -Name "notepad" or -Id <pid>. Note that Get-Process -Name "chrome" | Stop-Process kills every instance at once, which is risky; narrow the set with Where-Object { $_.Id -eq $pid } or review it with Select-Object Id,Path before pulling the trigger.
How do I quickly explore what a cmdlet can do while debugging a script?
Three tools cover it: Get-Command lists every cmdlet, function and alias so you can confirm the name exists and see what short names like ls, cd and where actually resolve to; Get-Help Get-Process opens the documentation, and -Detailed shows full parameters and examples; Get-Member inspects the properties and methods of what the pipeline emits, which is usually where a wrong argument shows up. Keep environment tweaks in $profile and guard failures with try/catch/finally.
Enter-PSSession or Invoke-Command when working on a remote machine?
It depends on interaction. Invoke-Command -ComputerName Server01 -ScriptBlock { Get-Process } is one-shot and non-interactive: the block runs remotely, the output prints locally, and the session drops when it finishes — ideal for sweeps. Enter-PSSession -ComputerName Server01 opens a persistent session where you sit inside the remote context, can re-run commands, read Get-Help and set variables, with your changes applied on the target until you exit. Check reachability with Test-NetConnection first.
How do I turn a query result into a readable table or a CSV file?
Append a formatting cmdlet to the pipeline: Format-Table Name,Id -AutoSize auto-sizes the columns, switch to Format-List Name,Id when there are too many properties to fit on one line, and Format-Wide Name -Column 4 for multi-column output. When you need the data on disk, Export-Csv data.csv -NoTypeInformation (the flag drops the type header so other tools can parse it) and read it back with Import-Csv. Filter and sort first — for example Get-Process | Sort-Object WS -Descending | Select-Object -First 10.
Official References
Each command links to its official documentation below, so you can verify the latest usage and read deeper.
Maintained by LaoHand
Publicly updated on Jul 21, 2026, continuously proofread against official docs.
Contact Us
Wrong command or description? Send us corrections, business inquiries or product feedback by email.
Contact Us