PowerShell

Windows 的现代化命令行 Shell 与脚本语言,基于 .NET,操作对象而非纯文本。PowerShell 7+ 为跨平台版本。

基础操作

Get-Help <命令>            # 查看帮助
Get-Help <命令> -Examples  # 查看示例
Clear-Host                 # 清屏(alias: cls)

常用别名

别名完整命令
ls / dirGet-ChildItem
cdSet-Location
catGet-Content
rmRemove-Item
cpCopy-Item
mvMove-Item
echoWrite-Output
pwdGet-Location

文件与目录

Get-ChildItem                                    # 列出文件
Get-ChildItem -Hidden                            # 包含隐藏文件
Get-ChildItem -Recurse -Filter "*.log"           # 递归查找
 
New-Item -ItemType Directory -Name mydir         # 创建目录
Remove-Item -Recurse -Force mydir                # 递归删除
 
Copy-Item src.txt dest.txt
Move-Item src.txt dest.txt
Remove-Item file.txt -Force

文件内容

Get-Content file.txt                             # 读取内容
Get-Content file.txt -Tail 20                    # 最后 20 行
Set-Content file.txt "内容"                      # 写入(覆盖)
Add-Content file.txt "内容"                      # 追加
 
Select-String "关键词" file.txt                  # 查找字符串(类似 grep)
Select-String -Pattern "正则" -Path "*.log"

对象与管道

PowerShell 管道传递的是对象,不是文本:

# 过滤
Get-Process | Where-Object { $_.CPU -gt 10 }
Get-Process | Where-Object Name -like "chrome*"
 
# 选择属性
Get-Process | Select-Object Name, CPU, Id
 
# 排序
Get-Process | Sort-Object CPU -Descending
 
# 统计
Get-ChildItem | Measure-Object -Property Length -Sum
 
# 格式化
Get-Process | Format-Table Name, CPU, Id

变量

$name = "World"
Write-Output "Hello, $name!"
 
[int]$count = 42          # 强类型
 
$arr = @(1, 2, 3)         # 数组
$arr[0]
 
$map = @{ key = "value"; num = 42 }   # 哈希表
$map["key"]

条件与循环

if ($x -gt 10) {
    Write-Output "大于10"
} elseif ($x -eq 10) {
    Write-Output "等于10"
} else {
    Write-Output "小于10"
}
 
# 比较运算符:-eq -ne -gt -ge -lt -le -like -match -contains -in
 
foreach ($item in $arr) { Write-Output $item }
 
for ($i = 0; $i -lt 5; $i++) { Write-Output $i }
 
1..5 | ForEach-Object { $_ * 2 }

函数

function Get-Greeting {
    param(
        [string]$Name = "World",
        [switch]$Loud
    )
    $msg = "Hello, $Name!"
    if ($Loud) { $msg = $msg.ToUpper() }
    return $msg
}
 
Get-Greeting -Name "Alice"
Get-Greeting -Name "Bob" -Loud

错误处理

try {
    Get-Item "不存在的文件" -ErrorAction Stop
} catch {
    Write-Error "出错了: $_"
} finally {
    Write-Output "无论如何都执行"
}

网络与系统

Test-Connection google.com              # 类似 ping
Invoke-WebRequest https://example.com   # HTTP 请求
Resolve-DnsName example.com             # DNS 查询
 
Get-Process
Stop-Process -Id 1234 -Force
Stop-Process -Name "notepad"
 
Get-Service
Start-Service -Name "服务名"
Stop-Service -Name "服务名"

环境变量

$env:PATH                               # 读取
$env:MY_VAR = "value"                   # 设置(当前会话)
 
# 持久化(用户级)
[System.Environment]::SetEnvironmentVariable("MY_VAR", "value", "User")

脚本执行策略

Get-ExecutionPolicy                     # 查看当前策略
Set-ExecutionPolicy RemoteSigned        # 允许本地脚本(需管理员)

相关文档