我编写了一个用于重启网络上计算机的脚本。它运行良好,唯一的问题是主机中会弹出错误消息。该脚本会从一个txt文件($Computers
)中提取系统名称列表。我用一个我能访问的系统测试了该脚本,并在列表中添加了单词“wrench”,以模拟一个不在网络上的系统。测试脚本时,它在查找“wrench”时抛出了一条错误消息。以下是我目前脚本实际重启部分的内容:
#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
Restart-Computer -ComputerName $Computers -Wait -For PowerShell -Delay 2 -Force -Timeout 1800 # Restarts all listed systems at once
"----------------------------------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"
}
}
“Wrench”不会破坏脚本,据我所知,但我更希望脚本只是悄悄地处理它找不到的系统,只需将其附加到日志中,而不是在主机中抛出错误消息。