I have written a script for restarting computers on a network. I have it working just fine, the one issue I am running into is error messages popping up in the host. The script pulls a list of system names from a txt file ($Computers
). I tested the script with one system I was able to access and the word "wrench" in the list to simulate a system that isn't on the network. When testing the script, it threw out an error message when looking for "wrench". Here's what I have right now for the actual restart portion of my script:
#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" doesn't break the script, not from what I can tell, but I would prefer the script to just quietly handle systems it can't find by only appending it to the log and not throwing an error message in the host as well.
You should be able to add -ErrorAction SilentlyContinue to the command that is throwing an error for you. See: https://serverfault.com/questions/336121/how-to-ignore-an-error-in-powershell-and-let-it-continue