Skip to content

PowerShell

PowerShell 简介

PowerShell 是微软开发的任务自动化和配置管理框架,由命令行 Shell 和脚本语言组成。它基于 .NET Framework,提供了强大的对象处理能力。

PowerShell 版本

版本说明
PowerShell 5.1Windows 内置版本
PowerShell 7.x跨平台新版本

启动 PowerShell

cmd
powershell                         # 启动 PowerShell
pwsh                               # 启动 PowerShell 7
powershell -ExecutionPolicy Bypass # 绕过执行策略

基本命令

cmdlet 命令格式

powershell
Verb-Noun -Parameter Value

示例:

powershell
Get-Process
Get-Service
Get-ChildItem
New-Item
Remove-Item

常用动词

动词说明
Get获取
Set设置
New创建
Remove删除
Add添加
Clear清除
Start启动
Stop停止
Enable启用
Disable禁用
Write写入
Read读取

获取帮助

Get-Help

powershell
Get-Help Get-Process
Get-Help Get-Process -Full
Get-Help Get-Process -Examples
Get-Help Get-Process -Online
Get-Help Get-Process -Detailed
Get-Help about_*                   # 查看概念帮助
Update-Help                        # 更新帮助文件

其他帮助方式

powershell
Get-Command                        # 列出所有命令
Get-Command *process*              # 搜索命令
Get-Command -Verb Get              # 按动词搜索
Get-Command -Noun Process          # 按名词搜索
Get-Alias                          # 列出别名
Get-Member                         # 查看对象成员

变量

变量定义

powershell
$name = "PowerShell"               # 字符串
$number = 42                       # 整数
$pi = 3.14                         # 浮点数
$trueValue = $true                 # 布尔值
$array = @(1, 2, 3)                # 数组
$hash = @{a=1; b=2; c=3}           # 哈希表

变量类型

powershell
[string]$name = "text"
[int]$number = 42
[double]$pi = 3.14
[bool]$flag = $true
[array]$arr = @(1, 2, 3)
[hashtable]$hash = @{a=1}
[datetime]$date = Get-Date

特殊变量

变量说明
$_当前管道对象
$args参数数组
$true
$false
$null
$PWD当前目录
$HOME用户主目录
$HOST主机信息
$PID当前进程 ID
$PSVersionTablePowerShell 版本信息
$Error错误数组
$LASTEXITCODE上一个程序退出码

数据结构

数组

powershell
$arr = @(1, 2, 3, 4, 5)
$arr = 1..5                        # 范围数组
$arr[0]                            # 第一个元素
$arr[-1]                           # 最后一个元素
$arr[0..2]                         # 前三个元素
$arr.Count                         # 元素个数
$arr += 6                          # 添加元素
$arr -contains 3                   # 是否包含
$arr -join ","                     # 连接为字符串

哈希表

powershell
$hash = @{
    Name = "John"
    Age = 30
    City = "Beijing"
}
$hash.Name                         # 访问值
$hash["Name"]                      # 访问值
$hash.Add("Email", "john@example.com")  # 添加键值对
$hash.Remove("Age")                # 删除键值对
$hash.Keys                         # 所有键
$hash.Values                       # 所有值
$hash.ContainsKey("Name")          # 是否包含键

对象

powershell
$obj = New-Object PSObject -Property @{
    Name = "John"
    Age = 30
}
$obj | Add-Member -MemberType NoteProperty -Name "City" -Value "Beijing"
$obj.Name

流程控制

条件判断

powershell
if ($a -gt $b) {
    Write-Host "a > b"
} elseif ($a -eq $b) {
    Write-Host "a = b"
} else {
    Write-Host "a < b"
}

比较运算符:

运算符说明
-eq等于
-ne不等于
-gt大于
-lt小于
-ge大于等于
-le小于等于
-like模式匹配
-notlike不匹配
-match正则匹配
-notmatch不匹配正则
-contains包含
-notcontains不包含
-in在集合中
-notin不在集合中

switch 语句

powershell
switch ($value) {
    1 { Write-Host "One" }
    2 { Write-Host "Two" }
    3 { Write-Host "Three" }
    default { Write-Host "Other" }
}

switch -regex ($value) {
    "^[0-9]$" { Write-Host "Single digit" }
    "^[a-z]$" { Write-Host "Single letter" }
    default { Write-Host "Other" }
}

循环

for 循环

powershell
for ($i = 0; $i -lt 10; $i++) {
    Write-Host $i
}

foreach 循环

powershell
foreach ($item in $array) {
    Write-Host $item
}

$array | ForEach-Object {
    Write-Host $_
}

while 循环

powershell
while ($i -lt 10) {
    Write-Host $i
    $i++
}

do-while 循环

powershell
do {
    Write-Host $i
    $i++
} while ($i -lt 10)

do-until 循环

powershell
do {
    Write-Host $i
    $i++
} until ($i -ge 10)

循环控制

powershell
break                              # 跳出循环
continue                           # 跳过本次
return                             # 返回

函数

函数定义

powershell
function SayHello {
    Write-Host "Hello, World!"
}
SayHello

带参数的函数

powershell
function Greet {
    param(
        [string]$Name,
        [int]$Age = 0
    )
    Write-Host "Hello, $Name! Age: $Age"
}
Greet -Name "John" -Age 30
Greet "John" 30

参数属性

powershell
function Test {
    param(
        [Parameter(Mandatory=$true)]
        [string]$Name,

        [Parameter(Position=0)]
        [string]$Value,

        [ValidateSet("A", "B", "C")]
        [string]$Option,

        [ValidateRange(1, 100)]
        [int]$Number,

        [ValidateNotNullOrEmpty()]
        [string]$Required
    )
}

返回值

powershell
function Add {
    param($a, $b)
    return $a + $b
}

function GetInfo {
    $name = "John"
    $age = 30
    return @{
        Name = $name
        Age = $age
    }
}

管道

管道基础

powershell
Get-Process | Where-Object {$_.CPU -gt 100}
Get-Service | Where-Object {$_.Status -eq "Running"}
Get-ChildItem | Select-Object Name, Length
Get-Process | Sort-Object CPU -Descending | Select-Object -First 10

常用管道命令

powershell
Where-Object                       # 过滤
Select-Object                      # 选择
Sort-Object                        # 排序
ForEach-Object                     # 遍历
Group-Object                       # 分组
Measure-Object                     # 统计
Compare-Object                     # 比较
Tee-Object                         # 分支输出

管道示例

powershell
Get-Process | Where-Object {$_.WorkingSet -gt 100MB} | Sort-Object WorkingSet -Descending
Get-ChildItem -Recurse | Where-Object {$_.Extension -eq ".txt"} | Measure-Object -Property Length -Sum
Get-EventLog -LogName Application -EntryType Error | Select-Object -First 10
Get-Service | Where-Object {$_.Status -eq "Stopped"} | Start-Service

文件操作

文件读写

powershell
Get-Content file.txt               # 读取文件
Get-Content file.txt -TotalCount 10  # 读取前10行
Get-Content file.txt -Tail 10      # 读取后10行
Set-Content file.txt "content"     # 写入文件
Add-Content file.txt "more"        # 追加内容
Clear-Content file.txt             # 清空文件

文件管理

powershell
Get-ChildItem                      # 列出目录
Get-ChildItem -Recurse             # 递归列出
Get-ChildItem -Filter *.txt        # 过滤文件
New-Item -Path file.txt -ItemType File  # 创建文件
New-Item -Path dir -ItemType Directory   # 创建目录
Copy-Item source dest              # 复制
Move-Item source dest              # 移动
Remove-Item path                   # 删除
Remove-Item path -Recurse -Force   # 强制递归删除
Rename-Item old new                # 重命名
Test-Path path                     # 测试路径是否存在

CSV 操作

powershell
Import-Csv data.csv                # 导入 CSV
Import-Csv data.csv | Where-Object {$_.Column -eq "value"}
Export-Csv output.csv -NoTypeInformation  # 导出 CSV
Get-Process | Export-Csv processes.csv
ConvertTo-Csv                      # 转换为 CSV 格式
ConvertFrom-Csv                    # 从 CSV 转换

JSON 操作

powershell
Get-Content data.json | ConvertFrom-Json
$obj = @{name="John"; age=30}
$obj | ConvertTo-Json
$obj | ConvertTo-Json -Depth 10
$obj | ConvertTo-Json | Set-Content output.json

XML 操作

powershell
[xml]$xml = Get-Content data.xml
$xml.SelectSingleNode("//element")
$xml | Select-Xml -XPath "//element"

字符串操作

字符串方法

powershell
$text = "Hello World"
$text.ToUpper()                    # 大写
$text.ToLower()                    # 小写
$text.Substring(0, 5)              # 截取
$text.Replace("World", "PowerShell")  # 替换
$text.Split(" ")                   # 分割
$text.Trim()                       # 去除首尾空格
$text.StartsWith("Hello")          # 开头匹配
$text.EndsWith("World")            # 结尾匹配
$text.Contains("llo")              # 包含
$text.IndexOf("o")                 # 查找位置
$text.Length                       # 长度

字符串格式化

powershell
$name = "John"
$age = 30
"Name: $name, Age: $age"
"Name: {0}, Age: {1}" -f $name, $age
"{0:N2}" -f 1234.5678              # 数字格式化
"{0:D8}" -f 123                    # 整数补零
"{0:P}" -f 0.25                    # 百分比

正则表达式

powershell
"text" -match "pattern"            # 匹配
$text -replace "pattern", "new"    # 替换
$text -split "pattern"             # 分割
[regex]::Matches($text, "pattern") # 所有匹配
[regex]::Replace($text, "pattern", "new")

远程操作

Enter-PSSession

powershell
Enter-PSSession -ComputerName server01
Enter-PSSession -ComputerName server01 -Credential domain\user
Exit-PSSession

Invoke-Command

powershell
Invoke-Command -ComputerName server01 -ScriptBlock { Get-Process }
Invoke-Command -ComputerName server01,server02 -ScriptBlock { Get-Service }
Invoke-Command -ComputerName server01 -FilePath script.ps1

New-PSSession

powershell
$session = New-PSSession -ComputerName server01
Invoke-Command -Session $session -ScriptBlock { Get-Process }
Remove-PSSession $session

脚本执行

执行策略

powershell
Get-ExecutionPolicy                # 查看执行策略
Set-ExecutionPolicy RemoteSigned   # 设置执行策略
Set-ExecutionPolicy -Scope CurrentUser RemoteSigned

执行策略:

  • Restricted: 不允许执行脚本
  • RemoteSigned: 本地脚本可执行,远程脚本需要签名
  • AllSigned: 所有脚本需要签名
  • Unrestricted: 允许所有脚本
  • Bypass: 不阻止任何脚本

运行脚本

powershell
.\script.ps1
powershell -File script.ps1
powershell -ExecutionPolicy Bypass -File script.ps1

错误处理

try-catch

powershell
try {
    Get-Content "nonexistent.txt" -ErrorAction Stop
}
catch {
    Write-Host "Error: $_"
}
finally {
    Write-Host "Cleanup"
}

$ErrorActionPreference

powershell
$ErrorActionPreference = "Stop"
$ErrorActionPreference = "Continue"
$ErrorActionPreference = "SilentlyContinue"

模块管理

模块操作

powershell
Get-Module                         # 已加载模块
Get-Module -ListAvailable          # 可用模块
Import-Module ModuleName           # 导入模块
Remove-Module ModuleName           # 移除模块
Find-Module *sql*                  # 搜索模块
Install-Module ModuleName          # 安装模块
Update-Module ModuleName           # 更新模块
Uninstall-Module ModuleName        # 卸载模块

下一步学习