一、条件判断:像交通信号灯一样控制流程

在PowerShell中,if-elseswitch就像马路上的红绿灯,决定代码该走哪条路。比如检查服务是否运行:

# 技术栈:PowerShell 7.x
$service = Get-Service -Name "WinRM"

# 简单的if-else判断
if ($service.Status -eq "Running") {
    Write-Host "服务正在运行,无需操作" -ForegroundColor Green
} 
else {
    Start-Service $service.Name
    Write-Host "服务已启动" -ForegroundColor Yellow
}

# 更清晰的switch版本
switch ($service.Status) {
    "Running" { Write-Host "状态正常" }
    "Stopped" { Start-Service $service.Name }
    default   { Write-Host "状态异常:$_" }
}

注意

  • -eq是严格比较运算符,区分大小写(用-ieq忽略大小写)
  • switchdefault分支处理意外情况,类似else

二、循环结构:让重复工作自动化

1. foreach:处理集合的利器

像快递员派件一样遍历数组:

# 技术栈:PowerShell 5.1+
$files = Get-ChildItem -Path "C:\Logs\*.log"

foreach ($file in $files) {
    # 处理超过1MB的日志文件
    if ($file.Length -gt 1MB) {
        Compress-Archive -Path $file.FullName -DestinationPath "C:\Backup\$($file.Name).zip"
        Write-Host "已压缩:$($file.Name)"
    }
}

2. while:当条件满足时持续工作

适合处理不确定次数的任务,比如等待进程退出:

$process = Start-Process notepad -PassThru
$timeout = 10  # 秒

while ($process.HasExited -eq $false -and $timeout -gt 0) {
    Start-Sleep -Seconds 1
    $timeout--
    Write-Host "等待进程退出,剩余$timeout秒..."
}

if ($timeout -eq 0) {
    $process | Stop-Process -Force
}

三、优化技巧:让逻辑更高效

1. 提前退出减少嵌套

returnbreak避免深层嵌套:

function Test-Connection {
    param($server)
    
    # 快速失败模式
    if (-not (Test-NetConnection $server -Port 3389).TcpTestSucceeded) {
        Write-Warning "端口不通!"
        return $false
    }
    
    # 正常处理逻辑...
}

2. 管道结合Where-Object过滤

替代循环内的if判断:

Get-Process | Where-Object { $_.CPU -gt 100 } | Stop-Process

四、实战场景与陷阱规避

典型场景

  • 批量重命名文件时检查名称冲突
  • 部署脚本中分阶段验证环境

常见坑点

  1. 比较$null要用$var -eq $null,直接if ($var)可能误判
  2. 循环修改集合时,建议先复制集合:
$originalList = @(1,2,3)
$tempList = $originalList.Clone()

foreach ($item in $tempList) {
    if ($item -eq 2) {
        $originalList.Remove($item)
    }
}

性能对比

  • 处理10000项时,foreachForEach-Object快约3倍
  • 但管道操作(|)代码可读性更好