Escrevi um script para reiniciar computadores em uma rede. Ele está funcionando perfeitamente, mas o único problema que estou enfrentando são mensagens de erro aparecendo no host. O script extrai uma lista de nomes de sistemas de um arquivo txt ( $Computers
). Testei o script com um sistema que consegui acessar e a palavra "wrench" na lista para simular um sistema que não está na rede. Ao testar o script, ele gerou uma mensagem de erro ao procurar por "wrench". Aqui está o que tenho até o momento para a parte de reinicialização do meu 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" não quebra o script, pelo que sei, mas eu preferiria que o script apenas lidasse silenciosamente com os sistemas que ele não consegue encontrar, apenas anexando-o ao log e não exibindo uma mensagem de erro no host também.
Você deve conseguir adicionar -ErrorAction SilentlyContinue ao comando que está gerando o erro. Consulte: https://serverfault.com/questions/336121/how-to-ignore-an-error-in-powershell-and-let-it-continue