Reputation: 3551
I have a PowerShell script that restarts servers listed in a file.
foreach ($server in $servers) {
try {
cmd /c "shutdown.exe /r /f /m \\$server /t 0 /d p:0:0 /c 'PlannedRestart'"
"$server`tRestarted"
"$server`tRestarted" | Out-File -FilePath .\RestartServers_LOG.txt -Append
} catch {
"$server`t" + cmd /c ">&1"
"$server`t" + cmd /c "dir > .\RestartServers_LOG.txt 2>&1"
}
}
I am trying to catch any errors that may occur from the CMD to output on the PowerShell session as well as to a file in the CURRENT directory, so in PowerShell that would be .\
but I don't know what the current directory specification is for CMD. Unless its the same thing?
Essentially, I am hoping to accomplish something similar to how we can capture the exception message of PowerShell like this:
"$server`t" + $_.Exception.Message.ToString().Split(":")[1].Replace("`n","") |
Out-File -FilePath .\RestartServers_LOG.txt -Append
but CMD doesn't deal with exceptions like PowerShell, and instead STDERR.
Note: I am using the command shutdown.exe
because PowerShell doesn't have ability to restart "planned" or "unplanned" unfortunately.
Upvotes: 0
Views: 144
Reputation: 200503
Just do it the PoSh way:
$params = '/r', '/f',
'/t', '0',
'/d', 'p:0:0',
'/c', 'PlannedRestart'
$servers | ForEach-Object {
$output = & shutdown.exe /m "\\${_}" @params 2>&1
if ($LastExitCode -eq 0) {
"{0}`tRestarted" -f $_
} else {
"{0}`tRestart failed:`t{1}" -f $_, $output
}
} | Set-Content '.\RestartServers_LOG.txt'
External commands don't throw exceptions in the first place, so your try..catch
wouldn't do anything anyway.
Upvotes: 1