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.

SysOps·58 commands·Last updated 2026-07-21
powershellwindowsScriptingAutomationshell

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-Command
List all available PowerShell commands (cmdlets, functions, aliases)
Get-Help Get-Process
View command help, add -Detailed for more info
Get-Member
View properties and methods of pipeline objects
Get-Verb
List all PowerShell-approved verbs
Get-Alias
List all command aliases

File & Directory 8

Get-ChildItem
List directory contents, similar to ls/dir
Set-Location ..
Change directory, similar to cd
New-Item -ItemType Directory -Path C:\NewDir
Create new directory or file
Copy-Item src.txt dst.txt
Copy file or directory, similar to cp
Move-Item src.txt dst.txt
Move or rename file, similar to mv
Remove-Item file.txt
Delete file or directory, similar to rm
Rename-Item old.txt new.txt
Rename file or directory
Test-Path C:\path
Check if path exists, returns True/False

Content Operations 8

Get-Content file.txt
Read file content, similar to cat
Set-Content file.txt "text"
Write content to file (overwrite)
Add-Content file.txt "text"
Append content to file
Out-File output.txt
Write output to file
Export-Csv data.csv -NoTypeInformation
Export objects to CSV file
Import-Csv data.csv
Import objects from CSV file
ConvertTo-Json
Convert object to JSON format
ConvertFrom-Json
Create object from JSON string

Pipeline & Filtering 6

Where-Object { $_.Name -eq "svchost" }
Filter objects, similar to grep, can use where alias
Select-Object -First 10 Name,Id
Select object properties or first N items
Sort-Object Name -Descending
Sort objects by property
Group-Object Status
Group objects by property
Measure-Object -Sum -Average
Calculate numeric statistics (sum, average, etc.)
ForEach-Object { $_ * 2 }
Perform operation on each pipeline object

Process & Service 9

Get-Process
List all running processes, similar to ps
Get-Process -Name "chrome"
Find process by name
Stop-Process -Name "notepad"
Stop a process, similar to kill
Start-Process notepad.exe
Start a new process
Get-Service
List all Windows services
Start-Service Spooler
Start a service
Stop-Service Spooler
Stop a service
Restart-Service Spooler
Restart a service
Set-Service Spooler -StartupType Automatic
Set service startup type (Automatic/Manual/Disabled)

Network & Remote 6

Test-Connection 8.8.8.8
Test network connectivity, similar to ping
Test-NetConnection google.com -Port 443
Advanced network diagnostics, test port connectivity
Invoke-WebRequest -Uri https://api.example.com
Send HTTP/HTTPS request, similar to curl
Invoke-RestMethod -Uri https://api.example.com
Send REST API request, auto-parses JSON/XML
Enter-PSSession -ComputerName Server01
Enter remote PowerShell session, similar to SSH
Invoke-Command -ComputerName Server01 -ScriptBlock { Get-Process }
Execute command on remote machine

Scripting 8

$name = "World"
Define variable with $ prefix
$array = 1,2,3; $array[0]
Array definition and index access
$hash = @{ Name = "Tom"; Age = 30 }
Hashtable (dictionary) definition
if ($val -gt 10) { "big" } else { "small" }
Conditional, -gt/-lt/-eq for comparison
switch ($val) { 1 { "one" } default { "?" } }
Switch multi-branch condition
foreach ($item in $items) { $item }
Iterate over array or collection
function Say-Hello { param($name) "Hello $name" }
Define function with parameters
try { 1/0 } catch { "error: $_" } finally { "done" }
Exception handling try/catch/finally

System Management 8

Get-Date
Get current date and time
Set-Date "2026-01-01"
Set system date and time
Get-WmiObject Win32_Processor
Query system info via WMI (CPU)
Get-CimInstance Win32_LogicalDisk
Query disk info via CIM (recommended over WMI)
Format-Table Name,Id -AutoSize
Table format output with auto-sized columns
Format-List Name,Id
List format output, one property per line
Format-Wide Name -Column 4
Wide format output, multi-column display
Get-EventLog -LogName System -Newest 10
View system event log (latest 10 entries)

Parameter matrix

ParameterEffectExample
Get-CommandSupply the filesystem or registry path a cmdlet acts on; when omitted PowerShell uses the current location.Get-Command
Get-Help <Cmd> -DetailedWalk every child directory as well, so a search is not limited to the top level.Get-Help Get-Process -Detailed
Get-MemberRestrict results with the provider wildcard syntax, which is far faster than piping into Where-Object.Get-Process | Get-Member
Get-VerbInclude hidden items and let Remove-Item delete read-only files that would otherwise raise an error.Get-Verb
Get-AliasSuppress non-terminating error records so a loop over many paths does not flood the console.Get-Alias
Get-ChildItemPrint 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 DirectoryStop Export-Csv from writing the #TYPE header row, which otherwise breaks naive CSV parsers.New-Item -ItemType Directory -Path D:/NewDir
Copy-Item / Move-ItemFlatten a nested object into the pipeline so its members become first-class results.Move-Item src.txt dst.txt
Remove-ItemRun the cmdlet against a remote machine through WinRM (implicit remoting).Remove-Item file.txt
Rename-ItemAutomatic variable holding the directory of the running script, safer than relative paths in scheduled tasks.Rename-Item old.txt new.txt
Test-PathChoose 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-JsonJSON 字符串转对象$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_ProcessorWMI 查询硬件信息Get-WmiObject Win32_Processor
Get-CimInstance Win32_LogicalDiskCIM 查询磁盘信息(推荐)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

  1. 1Confirm which cmdlet a name actually resolves to

    Get-Process | Select-Object -First 1 | Get-Member

    CommandType tells you whether the name is an Alias, Function or Cmdlet, and Definition shows what it maps to.

  2. 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 -AutoSize

    Listing parameters by name is the reliable way to confirm that -Filter, -Recurse and -LiteralPath exist on the installed version.

  3. 3Inspect every property an object carries

    Get-Service Spooler | Format-List Name,Status,StartType

    Get-Member lists the real property and method names, which is how you find the field to filter on.

  4. 4Surface the underlying error record instead of the formatted message

    Test-Connection 8.8.8.8; Test-NetConnection api.example.com -Port 443

    The full error record contains the category, the target object and the fully qualified error id.

  5. 5Measure what a pipeline produced before trusting it

    Invoke-RestMethod -Uri https://api.example.com/data | ConvertTo-Json

    The Count property tells you whether a filter or a Select-Object narrowed the set more than you intended.

  6. 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. 7在远程机器上执行诊断命令

    Invoke-Command -ComputerName Server01 -ScriptBlock { Get-Service | Select-Object -First 5 Name,Status }

    结果会以带远程主机前缀的形式返回,本地不改动任何状态。若需要多步交互式排查,改用 Enter-PSSession -ComputerName Server01 进入会话。

  8. 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_repos

Invoke-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