[PowerShell 入门教程] 第9.5天(间章):PowerShell 常见 Cmdlet 速查手册

📅 第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


🔑 核心原则总结

  1. 管道优先Get-X | Where Y | Select Z 是 PowerShell 思维核心
  2. 对象而非文本 :避免 Write-Host,保持对象流(便于后续处理)
  3. 参数缩写 :常用参数可缩写(如 -Path-Pa),但脚本中建议写全
  4. 帮助即文档Get-Help <Cmdlet> -Examples 是最佳学习入口
  5. 安全默认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-HelpGet-Command 动态探索。

课后习题,使用这些Cmdlet,查阅Microsoft说明书例如

查阅Get-Content命令和它的示例

Get-Content (Microsoft.PowerShell.Management) - PowerShell | Microsoft Learn

相关推荐
JaguarJack1 天前
推荐 PHP 属性(Attributes) 简洁读取 API 扩展包
后端·php·服务端
BingoGo1 天前
推荐 PHP 属性(Attributes) 简洁读取 API 扩展包
php
JaguarJack2 天前
告别 Laravel 缓慢的 Blade!Livewire Blaze 来了,为你的 Laravel 性能提速
后端·php·laravel
郑州光合科技余经理2 天前
代码展示:PHP搭建海外版外卖系统源码解析
java·开发语言·前端·后端·系统架构·uni-app·php
feifeigo1233 天前
matlab画图工具
开发语言·matlab
dustcell.3 天前
haproxy七层代理
java·开发语言·前端
norlan_jame3 天前
C-PHY与D-PHY差异
c语言·开发语言
多恩Stone3 天前
【C++入门扫盲1】C++ 与 Python:类型、编译器/解释器与 CPU 的关系
开发语言·c++·人工智能·python·算法·3d·aigc
QQ4022054963 天前
Python+django+vue3预制菜半成品配菜平台
开发语言·python·django
QQ5110082853 天前
python+springboot+django/flask的校园资料分享系统
spring boot·python·django·flask·node.js·php