知识速查表
本文档提供 PowerShell 常用命令和语法的快速参考,方便日常查阅。
基础语法
变量
$name = "value"
[int]$number = 42
[hashtable]$config = @{ Key = "Value" }
数据类型
| 类型 | 示例 |
|---|---|
| 字符串 | "Hello" 或 'Hello' |
| 整数 | 42 |
| 浮点数 | 3.14 |
| 布尔值 | $true, $false |
| 数组 | @(1, 2, 3) 或 1, 2, 3 |
| 哈希表 | @{Name = "Value"} |
| 空值 | $null |
运算符
| 类型 | 运算符 |
|---|---|
| 比较 | -eq, -ne, -gt, -lt, -ge, -le |
| 字符串 | -like, -match, -replace, -split, -join |
| 包含 | -in, -notin, -contains, -notcontains |
| 逻辑 | -and, -or, -not, -xor |
| 类型 | -is, -isnot, -as |
| 范围 | 1..10 |
控制流
if ($condition) { } elseif ($condition) { } else { }
switch ($value) {
"option1" { }
"option2" { }
default { }
}
for ($i = 0; $i -lt 10; $i++) { }
foreach ($item in $collection) { }
while ($condition) { }
do { } while ($condition)
do { } until ($condition)
常用 Cmdlet
帮助与发现
| 命令 | 说明 |
|---|---|
Get-Help <cmd> | 获取帮助 |
Get-Command <pattern> | 查找命令 |
Get-Member | 查看对象成员 |
Get-Alias | 查看别名 |
Update-Help | 更新帮助文档 |
文件操作
| 命令 | 说明 |
|---|---|
Get-ChildItem | 列出目录内容 |
New-Item | 创建文件或目录 |
Copy-Item | 复制 |
Move-Item | 移动或重命名 |
Remove-Item | 删除 |
Get-Content | 读取文件内容 |
Set-Content | 写入文件内容 |
Add-Content | 追加内容 |
Test-Path | 检查路径是否存在 |
Join-Path | 拼接路径 |
Split-Path | 分割路径 |
进程与服务
| 命令 | 说明 |
|---|---|
Get-Process | 获取进程 |
Stop-Process | 停止进程 |
Start-Process | 启动进程 |
Get-Service | 获取服务 |
Start-Service | 启动服务 |
Stop-Service | 停止服务 |
Restart-Service | 重启服务 |
Set-Service | 修改服务属性 |
对象处理
| 命令 | 说明 |
|---|---|
Where-Object | 过滤对象 |
Select-Object | 选择属性 |
Sort-Object | 排序 |
Group-Object | 分组 |
Measure-Object | 统计 |
ForEach-Object | 遍历处理 |
Compare-Object | 比较 |
输出与格式化
| 命令 | 说明 |
|---|---|
Write-Host | 输出到控制台 |
Write-Output | 输出到管道 |
Write-Error | 输出错误 |
Write-Warning | 输出警告 |
Write-Verbose | 输出详细信息 |
Format-Table | 表格格式 |
Format-List | 列表格式 |
Format-Wide | 宽格式 |
Out-File | 输出到文件 |
Out-GridView | 图形化显示 |
导入导出
| 命令 | 说明 |
|---|---|
Export-Csv | 导出 CSV |
Import-Csv | 导入 CSV |
ConvertTo-Json | 转换为 JSON |
ConvertFrom-Json | 从 JSON 转换 |
Export-Clixml | 导出 XML |
Import-Clixml | 导入 XML |
Export-Clixml | 序列化对象 |
网络操作
| 命令 | 说明 |
|---|---|
Test-Connection | Ping 测试 |
Test-NetConnection | 网络连接测试 |
Invoke-WebRequest | HTTP 请求 |
Invoke-RestMethod | REST API 调用 |
远程管理
| 命令 | 说明 |
|---|---|
Enter-PSSession | 进入远程会话 |
Exit-PSSession | 退出远程会话 |
New-PSSession | 创建会话 |
Remove-PSSession | 删除会话 |
Invoke-Command | 远程执行命令 |
Enable-PSRemoting | 启用远程管理 |
模块管理
| 命令 | 说明 |
|---|---|
Get-Module | 获取模块 |
Import-Module | 导入模块 |
Remove-Module | 移除模块 |
Find-Module | 搜索模块 |
Install-Module | 安装模块 |
Update-Module | 更新模块 |
Uninstall-Module | 卸载模块 |
Publish-Module | 发布模块 |
函数定义
基本函数
function Get-Info {
param(
[string]$Name
)
return "Hello, $Name"
}
高级函数
function Get-Data {
[CmdletBinding()]
param(
[Parameter(Mandatory=$true, Position=0)]
[string]$Path,
[Parameter(ValueFromPipeline=$true)]
[string]$InputObject,
[ValidateSet("Option1", "Option2")]
[string]$Mode = "Option1"
)
begin { }
process { }
end { }
}
参数验证属性
| 属性 | 说明 |
|---|---|
[ValidateSet("a","b")] | 限制可选值 |
[ValidateRange(1,100)] | 限制数值范围 |
[ValidateLength(1,50)] | 限制字符串长度 |
[ValidatePattern("regex")] | 正则验证 |
[ValidateNotNullOrEmpty()] | 不允许空值 |
[ValidateScript({ })] | 自定义验证 |
错误处理
try {
} catch [System.IO.FileNotFoundException] {
} catch {
} finally {
}
ErrorAction 值
| 值 | 说明 |
|---|---|
Continue | 显示错误,继续执行 |
SilentlyContinue | 不显示错误,继续执行 |
Stop | 停止执行,触发 catch |
Ignore | 忽略错误,不记录 |
特殊变量
| 变量 | 说明 |
|---|---|
$_ | 管道当前对象 |
$? | 上一命令执行状态 |
$LASTEXITCODE | 外部程序退出码 |
$null | 空值 |
$true / $false | 布尔值 |
$PWD | 当前目录 |
$HOME | 用户主目录 |
$PID | 当前进程 ID |
$Error | 错误数组 |
$PROFILE | 配置文件路径 |
别名
| 别名 | 命令 |
|---|---|
? | Where-Object |
% | ForEach-Object |
dir | Get-ChildItem |
ls | Get-ChildItem |
cat | Get-Content |
rm | Remove-Item |
cp | Copy-Item |
mv | Move-Item |
cd | Set-Location |
pwd | Get-Location |
echo | Write-Output |
cls | Clear-Host |
kill | Stop-Process |
sleep | Start-Sleep |
sort | Sort-Object |
gc | Get-Content |
gci | Get-ChildItem |
gm | Get-Member |
iex | Invoke-Expression |
select | Select-Object |
measure | Measure-Object |
常用代码片段
获取系统信息
Get-ComputerInfo | Select-Object OsName, WindowsVersion, CsName
查找大文件
Get-ChildItem -Path C:\ -Recurse -ErrorAction SilentlyContinue |
Where-Object { $_.Length -gt 100MB } |
Sort-Object Length -Descending |
Select-Object FullName, @{N='Size(MB)';E={[math]::Round($_.Length/1MB,2)}}
批量处理文件
Get-ChildItem -Filter "*.txt" | ForEach-Object {
$content = Get-Content $_.FullName
}
远程执行
Invoke-Command -ComputerName "Server01", "Server02" -ScriptBlock {
Get-Service -Name "WinRM"
}
JSON 处理
$json = Get-Content "config.json" | ConvertFrom-Json
$json.property
$json | ConvertTo-Json -Depth 10 | Set-Content "output.json"
HTTP 请求
$response = Invoke-RestMethod -Uri "https://api.example.com/data" -Method Get
$response = Invoke-RestMethod -Uri "https://api.example.com/data" -Method Post -Body ($data | ConvertTo-Json) -ContentType "application/json"
日志函数
function Write-Log {
param([string]$Message, [string]$Level = "Info")
$timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
Write-Host "[$timestamp] [$Level] $Message"
}
重试逻辑
$maxRetries = 3
$retry = 0
do {
$retry++
try {
break
} catch {
if ($retry -ge $maxRetries) { throw }
Start-Sleep -Seconds 2
}
} while ($retry -lt $maxRetries)
正则表达式
"hello123" -match "\d+"
"hello123" -replace "\d+", "456"
"hello123" -split "\d+"
Select-String -Path "*.log" -Pattern "Error"
日期时间
Get-Date
Get-Date -Format "yyyy-MM-dd HH:mm:ss"
(Get-Date).AddDays(-7)
[datetime]::Parse("2024-01-15")
字符串操作
"text".ToUpper()
"text".ToLower()
"text".Length
"text".Substring(0, 2)
"text".Replace("t", "T")
"text".Split(",")
"text".Trim()
"text".StartsWith("te")
"text".EndsWith("xt")
"text".Contains("ex")