PowerShell ForEach循环遇无OpenSSH服务服务器时中断问题排查
问题根源
- 远程操作未做容错:当远程服务器无法连接、无访问权限,或找不到SSH服务时,PowerShell默认会抛出终止错误,直接打断循环,后续服务器不再被处理。
- CSV格式不统一:else分支用
Add-Content手动拼接字符串,和Export-Csv生成的结构化CSV格式不匹配,会导致文件损坏或后续读取异常。 - 空值判断逻辑错误:
[string]::IsNullOrEmpty($Services)是用于判断字符串的,但$Services是数组类型,无匹配服务时为空数组,这个判断完全不生效,会导致逻辑走岔。
修复后的脚本
# 检查OpenSSH服务安装情况 $Servers = Get-Content -Path C:\temp\2019servers.txt $outputPath = "c:\temp\2019_openssh_services.csv" # 先清理旧文件,避免重复追加数据 if (Test-Path $outputPath) { Remove-Item $outputPath -Force } ForEach ($Server in $Servers) { # 屏蔽远程操作错误,防止循环中断 $Services = Get-Service -Name "SSH*" -ComputerName $server -ErrorAction SilentlyContinue | Select-Object -Property Name, StartType, Status, DisplayName, MachineName if ($Services) { Write-Host "$Server 存在OpenSSH服务" $Services | Export-Csv -Path $outputPath -NoTypeInformation -Append -Force } else { Write-Host "$Server 未安装OpenSSH服务或无法访问" # 生成与CSV结构一致的对象,保证格式统一 [PSCustomObject]@{ Name = $null StartType = $null Status = $null DisplayName = $null MachineName = $Server } | Export-Csv -Path $outputPath -NoTypeInformation -Append -Force } }
核心修复点
- 防止循环中断:给
Get-Service加上-ErrorAction SilentlyContinue,无论远程操作成功与否,循环都会继续处理下一台服务器。如果需要记录错误详情,可以改用-ErrorAction Stop并配合try/catch块捕获错误信息。 - 修正判断逻辑:直接用
if ($Services)判断是否存在服务,PowerShell会自动识别空数组,逻辑更准确。 - 统一CSV格式:不再用
Add-Content手动写入字符串,而是生成和正常服务条目结构一致的对象,确保CSV格式始终统一,后续读取不会出问题。 - 初始化输出文件:循环前先删除旧的CSV文件,避免多次运行时数据重复追加。
内容的提问来源于stack exchange,提问作者R_malde
相关产品推荐
相关产品推荐

