Cmdlet 基础
Verb-Noun、Get-Help、Get-Command。
30 分钟
Cmdlet 基础
Cmdlet(发音 command-let)是 PowerShell 的最小命令单元,命名遵循 Verb-Noun(动词-名词),如 Get-ChildItem、Copy-Item。比 CMD 的 dir、copy 更一致、可发现。
学习目标
- 理解 Verb-Noun 命名约定
- 会用
Get-Help、Get-Command自学 cmdlet - 掌握常用文件与进程 cmdlet
核心内容
Verb-Noun 约定
常见动词:
| 动词 | 含义 | 示例 |
|---|---|---|
| Get | 读取 | Get-Process |
| Set | 修改 | Set-Location |
| New | 创建 | New-Item |
| Remove | 删除 | Remove-Item |
| Invoke | 调用 | Invoke-RestMethod |
别名:ls → Get-ChildItem,cd → Set-Location。脚本里建议写全名,便于阅读。
自学 cmdlet
Get-Command *-Item # 列出所有 *-Item cmdlet
Get-Help Copy-Item -Full # 完整帮助
Get-Help Invoke-RestMethod -Examples # 示例优先
Update-Help -Force # 更新本地帮助(需联网)
Tab 补全 cmdlet 名与参数名;Ctrl+C 中断长时间命令。
常用 cmdlet
Get-Location
Get-ChildItem H:\work\java-nav\deploy -Recurse -Filter *.ps1
Get-Process | Where-Object { $_.ProcessName -like "java*" }
Get-NetTCPConnection -LocalPort 8080 -ErrorAction SilentlyContinue
Invoke-RestMethod -Uri "http://127.0.0.1:8080/api/tracks"
Get-NetTCPConnection 排查端口占用,对应 Linux 的 ss -tlnp(linux-shell)。
参数写法
# 位置参数
Get-ChildItem H:\work\java-nav
# 命名参数(推荐)
Get-ChildItem -Path H:\work\java-nav -Filter "*.md" -Recurse
# 开关参数
Get-ChildItem -Force # 含隐藏文件
布尔开关:-WhatIf 预览、 -Confirm 确认,删除操作前先用 -WhatIf。