PowerShell 入门2: 使用帮助系统
PowerShell 入门 2:使用帮助系统
🎯 一、认识 PowerShell 帮助系统
1. 使用 Get-Help
查看命令说明
Get-Help Get-Service
或使用别名:
gsv
2. 更新帮助系统
Update-Help
3. 搜索包含关键词的命令(模糊搜索)
Help *log*
📌 例如查找和事件日志相关的命令(如 Get-EventLog
)。
🧩 二、Cmdlet 命名规范:动词-名词
PowerShell 中的命令遵循 动词-名词
结构,如:
Get-Process
Set-Date
Get-EventLog
📚 三、Get-EventLog 命令语法解析
Get-EventLog [-AsString] [-ComputerName <string[]>] [-List][<CommonParameters>]Get-EventLog [-LogName] <string>[[-InstanceId] <Int64[]>][-After <DateTime>] [-AsBaseObject][-Before <DateTime>] [-ComputerName <string[]>][-EntryType <string[]>] [-Index <Int32[]>][-Message <string>] [-Newest <int>][-Source <string[]>] [-UserName <string[]>][<CommonParameters>]
参数集说明:
-List
,-AsString
仅用于列出日志名称(参数集1)-LogName
,-Newest
,-EntryType
等用于读取具体日志内容(参数集2)-ComputerName
是两个参数集共享的
🔺 注意:不能同时混用两个参数集的参数
🧾 四、可选与必选参数
写法 | 含义 |
---|---|
[-Param <type>] | 可选参数(必须写参数名) |
[-Param] <type> | 必选参数 + 是位置参数 |
[[-Param] <type>] | 可选参数 + 是位置参数 |
- 方括号
[ ]
表示参数是可选的 - 可省略参数名(前提是该参数是位置参数且位置正确)
- 缩写参数名需唯一(如
-Li
表示-List
,但-L
不唯一会报错)
🧠 五、使用参数的最佳实践
✅ 推荐做法:
- 编写脚本或笔记时,总是使用完整参数名
Get-EventLog -LogName Application -Newest 20
- 熟练后在命令行交互中使用缩写
🧱 六、位置参数的判断方法
方法一:通过语法概要判断
示例:
[-LogName] <string> # 必选位置参数
[[-InstanceId] <int64[]>] # 可选位置参数
[-Before <datetime>] # 非位置参数(必须写参数名)
方法二:查看完整帮助文档
Help Get-EventLog -Full
输出段落示例:
-LogName <string>是否必需? True位置? 0接受通配符? False
🎚️ 七、开关参数与数据类型
1. Switch 参数
- 示例:
-AsString
- 无需指定值,只要写出来就等于启用
Get-EventLog -List -AsString
2. 常见数据类型说明
类型 | 示例 | 说明 |
---|---|---|
string | 'Application' | 含空格需加引号 |
int/int64 | 5 | 整数 |
datetime | 2025-08-05 | 日期格式自动解析 |
string[] | 'Server01','Server02' | 字符串数组,用逗号隔开 |
🔺 若字符串中有空格需加引号(如 "C:\Program Files"
)
📂 八、如何批量传递数组参数
可使用文件:
📁 computers.txt
Server01
Server02
Server03
Get-EventLog -LogName System -ComputerName (Get-Content computers.txt)
🔍 九、查看示例与“关于”主题
1. 只查看示例
Help Get-EventLog -Examples
2. 查看通用参数帮助
Help about_CommonParameters
3. 列出所有“about_”帮助主题
Help about*
常见 about_ 主题涵盖:
- 类型系统
- 错误处理
- 脚本变量作用域
- 管道行为
🧾 十、常用命令小结
命令 | 功能 |
---|---|
Help Get-EventLog -Full | 查看完整帮助与参数解释 |
Help Get-EventLog -Examples | 快速学习命令示例 |
Update-Help | 更新本地帮助文件 |
Help Get-EventLog -ShowWindow | GUI 帮助(仅限桌面系统) |
Get-Command Get-EventLog | 查看命令基本定义 |
(Get-Command Get-EventLog).Parameters[...] | 查看参数详情 |
Help about_CommonParameters | 查看通用参数详细说明 |
Help about* | 列出所有“about_”主题 |