📅 第9.5天(间章):PowerShell 常见 Cmdlet 速查手册
用好PowerShell还是需要多了解、多实际应用系统的Cmdlet
下面是 专为已有基础的学习者设计,系统梳理 7 大类高频实用 Cmdlet,涵盖:
- 过滤与选择
- 进程与服务管理
- 文件与目录操作
- 网络诊断与配置
- 实用工具(Utility)
- 控制台交互(ReadLine)
- 其他"宝藏"Cmdlet
每个 Cmdlet 均标注 最常用参数 、典型用法 和 避坑提示,可作为日常开发/运维的快速参考。
致我们终将逝去的青春 ---《YOYO原创彩蛋》
💡 建议:将本页打印为速查卡
致我们终将逝去的青春 ---《原创彩蛋》
一、过滤与选择(Filtering & Selection)
| Cmdlet | 常用参数 | 示例 | 说明 |
|---|---|---|---|
Where-Object (?) |
-Property, -EQ, 脚本块 {} |
`Get-Process | Where-Object CPU -gt 100 Get-Service |
Select-Object (select) |
-Property, -First, -ExpandProperty |
`Get-ChildItem | Select-Object Name, Length Get-ChildItem |
Sort-Object (sort) |
-Property, -Descending |
`Get-Process | Sort-Object WorkingSet -Descending |
Group-Object |
-Property |
`Get-WinEvent -LogName System -MaxEvents 100 | Group-Object LevelDisplayName` |
二、进程与服务管理
| Cmdlet | 常用参数 | 示例 | 说明 |
|---|---|---|---|
Get-Process (ps) |
-Name, -Id |
`Get-Process chrome, edge # 查看高CPU进程 Get-Process |
Where CPU -gt 50` |
Stop-Process |
-Name, -Force |
Stop-Process -Name notepad -Force |
强制结束进程 |
Get-Service |
-Name, -DisplayName |
`Get-Service bits, dhcp # 所有运行中的服务 Get-Service |
Where Status -eq Running` |
Start-Service / Stop-Service |
-Name |
Restart-Service spooler -PassThru |
重启打印服务并返回对象 |
Get-EventLog (旧) / Get-WinEvent (新) |
-LogName, -MaxEvents |
Get-WinEvent -LogName Application -MaxEvents 10 |
查看应用日志(推荐 Get-WinEvent) |
三、文件与目录管理
| Cmdlet | 常用参数 | 示例 | 说明 |
|---|---|---|---|
Get-ChildItem (ls, dir) |
-Path, -Recurse, -File, -Directory |
# 列出所有 .log 文件(含子目录) Get-ChildItem C:\Logs -Recurse -Include *.log -File |
遍历文件系统 |
New-Item |
-Path, -ItemType, -Value |
New-Item "C:\temp\readme.txt" -ItemType File -Value "Hello" New-Item "C:\projects" -ItemType Directory |
创建文件或目录 |
Copy-Item |
-Path, -Destination, -Recurse |
Copy-Item "C:\data\*" "D:\backup\" -Recurse -Force |
复制整个目录 |
Move-Item |
-Path, -Destination |
Move-Item "old.log" "archive\" |
移动或重命名 |
Remove-Item (rm, del) |
-Path, -Recurse, -Force |
Remove-Item "temp\*" -Recurse -Force |
删除文件/目录(强制) |
Get-Content (cat, type) |
-Path, -Tail, -TotalCount, -Raw |
# 查看日志最后10行<br>Get-Content "C:\app.log" -Tail 10 # 读取整个文件为单字符串 $text = Get-Content file.txt -Raw |
高效读取文件内容 |
Set-Content |
-Path, -Value, -Encoding |
Set-Content "config.txt" "debug=true"``` # 覆盖写入(不保留原内容)`` |
覆盖写入文件 |
Add-Content |
-Path, -Value, -Encoding |
Add-Content "audit.log" "$(Get-Date): User login"# 追加日志 |
追加内容到文件末尾 |
💡 Content 系列区别:
Set-Content:覆盖文件Add-Content:追加到末尾Get-Content -Raw:返回单字符串(适合正则全文匹配)Get-Content -Tail N:高效读大文件尾部(内存友好)
四、网络相关
| Cmdlet | 常用参数 | 示例 | 说明 |
|---|---|---|---|
Test-Connection |
-ComputerName, -Count, -Quiet |
# 快速检测是否在线<br>if (Test-Connection google.com -Count 1 -Quiet) {<br> Write-Host "Online"<br>} |
替代 ping |
Resolve-DnsName |
-Name, -Type |
Resolve-DnsName example.com -Type A |
DNS 查询(替代 nslookup) |
Get-NetIPAddress |
-AddressFamily, -InterfaceAlias |
`Get-NetIPAddress -AddressFamily IPv4 | Select InterfaceAlias, IPAddress` |
Invoke-WebRequest (iw) |
-Uri, -OutFile, -UseBasicParsing |
iw "https://example.com/file.zip" -OutFile "download.zip" |
下载文件(兼容无 IE 环境) |
Invoke-RestMethod (irm) |
-Uri, -Method, -Body |
$users = irm "https://jsonplaceholder.typicode.com/users"<br>$users[0].name |
自动解析 JSON/XML |
五、实用工具(Utility)
| Cmdlet | 常用参数 | 示例 | 说明 |
|---|---|---|---|
Measure-Command |
-Expression |
`$time = Measure-Command { Get-Process |
Where CPU -gt 10 } Write-Host "耗时: (time.TotalMilliseconds) ms"` |
Get-Date |
-Format, 方法如 .AddDays() |
$yesterday = (Get-Date).AddDays(-1)<br>$stamp = Get-Date -Format "yyyyMMdd_HHmmss" |
日期计算与格式化 |
ConvertTo-Json |
-Depth, -Compress |
`config = @{ Port=8080; SSL=true } $config |
ConvertTo-Json -Depth 3 |
Export-Csv |
-Path, -NoTypeInformation |
`Get-Process | Select Name, Id, CPU |
Out-File |
-FilePath, -Encoding, -Append |
`"Error: disk full" | Out-File app.log -Append -Encoding UTF8` |
六、控制台交互(ReadLine & Console)
| Cmdlet | 常用参数 | 示例 | 说明 |
|---|---|---|---|
Read-Host |
-Prompt, -AsSecureString |
$user = Read-Host "Username"<br>$pass = Read-Host "Password" -AsSecureString |
安全输入凭据 |
Write-Host |
-ForegroundColor |
Write-Host "[INFO] Starting..." -Fore Green<br>Write-Host "[ERROR] Failed!" -Fore Red |
仅用于用户提示(破坏管道) |
Write-Verbose |
-Message, 需 -Verbose 开关 |
function Test-App {<br> [CmdletBinding()]<br> param()<br> Write-Verbose "Connecting to DB..."<br>}<br>Test-App -Verbose |
可开关的调试信息 |
Clear-Host (cls) |
--- | cls # 清屏 |
清除控制台 |
Get-History |
-Count |
Get-History -Count 5 # 查看最近5条命令 |
命令历史回溯 |
七、其他"宝藏"Cmdlet
| Cmdlet | 示例 | 用途 |
|---|---|---|
Get-Member (gm) |
`Get-Process | Get-Member` |
Get-Command (gcm) |
Get-Command *json* # 找所有含 json 的命令 |
发现可用命令 |
Get-Help |
Get-Help Get-Process -Examples |
查看命令帮助和示例 |
Compare-Object |
$a = "file1", "file2 $b = "file2", "file3" Compare-Object $a $b |
比较两个集合差异 |
ForEach-Object (%) |
`1..3 | ForEach-Object { $_ * 2 } # 输出 2,4,6` |
Get-Error (PS 7+) |
Get-Process nonexistent -ErrorAction SilentlyContinue<br>Get-Error |
查看详细错误堆栈 |
🔑 终极建议:建立你的"Cmdlet 反射弧"
| 场景 | 推荐 Cmdlet |
|---|---|
| "我想看某个东西" | Get-*(如 Get-Process, Get-Service) |
| "我想改/删/建某个东西" | Set-*, Remove-*, New-* |
| "我想筛选结果" | Where-Object, Select-Object |
| "我想保存结果" | Export-Csv, Out-File, Set-Content |
| "我想知道这个对象有什么" | Get-Member |
| "我不记得命令名" | Get-Command *keyword* |
示例:建议如果日常运维一次输入的命令就用Alias,写脚本还是用全名。
get-process|? { $_.Name -match 'win'}|sort ProcessName
🔑 核心原则总结
- 管道优先 :
Get-X | Where Y | Select Z是 PowerShell 思维核心 - 对象而非文本 :避免
Write-Host,保持对象流(便于后续处理) - 参数缩写 :常用参数可缩写(如
-Path→-Pa),但脚本中建议写全 - 帮助即文档 :
Get-Help <Cmdlet> -Examples是最佳学习入口 - 安全默认 :
Remove-Item等危险操作默认带确认,用-Force或-Confirm:$false自动化
📌 附:常用别名速查
| 别名 | 全名 | 用途 |
|---|---|---|
? |
Where-Object |
过滤 |
% |
ForEach-Object |
循环 |
ls, dir |
Get-ChildItem |
列目录 |
cat, type |
Get-Content |
读文件 |
cp |
Copy-Item |
复制 |
mv |
Move-Item |
移动 |
rm, del |
Remove-Item |
删除 |
ps |
Get-Process |
查进程 |
gci |
Get-ChildItem |
列目录(完整别名) |
gi |
Get-Item |
获取项 |
💡 提示:用
Get-Alias查看所有别名;用Set-Alias创建自定义别名(不推荐在脚本中使用)
此间章可作为 日常开发速查表 ,建议结合 Get-Help 和 Get-Command 动态探索。
课后习题,使用这些Cmdlet,查阅Microsoft说明书例如
查阅Get-Content命令和它的示例
Get-Content (Microsoft.PowerShell.Management) - PowerShell | Microsoft Learn