跳到主要内容

知识速查表

本文档提供 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-ConnectionPing 测试
Test-NetConnection网络连接测试
Invoke-WebRequestHTTP 请求
Invoke-RestMethodREST 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
dirGet-ChildItem
lsGet-ChildItem
catGet-Content
rmRemove-Item
cpCopy-Item
mvMove-Item
cdSet-Location
pwdGet-Location
echoWrite-Output
clsClear-Host
killStop-Process
sleepStart-Sleep
sortSort-Object
gcGet-Content
gciGet-ChildItem
gmGet-Member
iexInvoke-Expression
selectSelect-Object
measureMeasure-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")