PowerShell批量重启脚本报错:如何静默处理不可达主机
解决PowerShell批量重启脚本的错误输出问题
要解决不可达主机导致控制台报错的问题,核心是捕获重启阶段的错误并仅记录到日志,同时保留原有验证逻辑。以下是修改后的完整核心代码及说明:
修改后的代码
#Actual restart portion (for privacy reasons, real file path replaced with "file-path") #Starts by moving most recent log to archive folder Get-ChildItem -Path "\\file-path\Computer Restarts\Logs" -Recurse -File | Move-Item -Destination "\\file-path\Computer Restarts\Logs\Archive" -Force #Determine script location, create new script, get current time and date $ScriptDir = Split-Path $script:MyInvocation.MyCommand.Path $Log = New-Item "\\file-path\Computer Restarts\Logs\$(Get-Date -f yyyy-MM-dd_hh-mm-ss) Restarts.txt" -ItemType File -Force $Date = Get-Date -Format "dd-MMM-yyyy hh:mm:ss" $Now = [datetime]::Now Clear-Host Write-Host `n `n `n Write-Host "Rebooting all computers and verifying reboot status..." `n `n Write-Host "Please standby, process may take up to 30 minutes..." `n `n # 逐个处理主机重启,捕获错误并记录到日志 foreach ($Computer in $Computers) { try { # 尝试重启主机,-ErrorAction Stop确保所有错误进入catch块 Restart-Computer -ComputerName $Computer -Wait -For PowerShell -Delay 2 -Force -Timeout 1800 -ErrorAction Stop Add-Content -Path $Log -Value "$Computer`: 重启命令已执行,等待验证状态..." } catch { # 记录重启失败的错误信息,控制台不输出错误 Add-Content -Path $Log -Value "$Computer`: 重启失败 - $($_.Exception.Message)" } } "----------------------------------Script executed on $Date----------------------------------" + "`r`n" | Out-File $Log -Append #First thing added to new log foreach($Computer in $Computers) #Checks each server to see if it has rebooted. Waits for confirmation before moving to next computer, skips computer if unresponsive after short time. { $LastBoot = (Get-CimInstance Win32_OperatingSystem -ComputerName $Computer -EA 0).LastBootUpTime $PingRequest = Test-Connection -ComputerName $Computer -Count 1 -Quiet if(($PingRequest -eq $true) -and ($LastBoot -gt $Now)) { Add-Content -Path $Log -Value "$Computer`: Reboot Successful." } elseif ($PingRequest -eq $false) { Add-Content -Path $Log -Value "$Computer`: Computer not detected, please confirm." } else { Add-Content -Path $Log -Value "$Computer`: Restart not detected, please restart computer manually. Last detected boot up time is $LastBoot" } }
关键修改说明
- 逐个处理主机重启:将原批量重启改为循环遍历每个主机,单独捕获每台机器的重启错误,避免一台失败导致整批报错。
- 错误捕获与日志记录:用
try/catch包裹Restart-Computer调用,并设置-ErrorAction Stop,确保所有错误(包括主机不可达、权限问题等)进入catch块,将错误信息写入日志,控制台不再显示错误。 - 保留原有验证逻辑:后续的重启状态验证逻辑保持不变,确保每台主机的最终状态都能被正确记录。
如果仍希望保持批量重启的效率,可将重启命令改为:
Restart-Computer -ComputerName $Computers -Wait -For PowerShell -Delay 2 -Force -Timeout 1800 -ErrorAction SilentlyContinue
但这种方式无法单独记录每台主机的重启失败原因,只能在后续验证阶段通过Ping或LastBoot时间判断状态,因此更推荐逐个处理的方案。
内容的提问来源于stack exchange,提问作者RustyAndroid
相关产品推荐
相关产品推荐

