Solved Powershell error handling or catching

April 10, 2017 at 07:07:49
Specs: Windows 7
I'm having trouble figuring out what to do with my script. I need to query AD to get a list of machines that have "host" in the name and then I need to check the status of the last Windows backup job and write it to a file. The code I have works but if the machine didn't have a backup job scheduled or isn't accessible I can't see it in my file. How can I get it to list those machines either with an error or just blank values?

import-module activedirectory;
$servers = get-adcomputer -filter {name -like "*host"};

$output =
foreach ($Server in $servers) {
Invoke-Command -ComputerName $Server.Name {get-wbjob -previous 1 | select-object starttime, endtime, hresult, errordescription}
}

$output | Sort-Object PSComputerName | Format-Table -Auto PSComputerName, HResult, ErrorDescription, StartTime, EndTime | Out-File c:\scripts\results.txt


See More: Powershell error handling or catching

Report •

#1
April 10, 2017 at 08:34:47
✔ Best Answer
Two different problems here. If you cannot connect to the system, you can use try/catch to handle it. If there are no WBJobs to get, you'll get none, so you need to check that.

Untested, but something like this:

import-module activedirectory; 
$servers = get-adcomputer -filter {name -like "*host"};
 
$output =
 foreach ($Server in $servers) {
   try { 
     Invoke-Command -ComputerName $Server.Name -ErrorAction Stop {
       $wbjob = get-wbjob -previous 1 -ErrorAction SilentlyContinue
       if ($wbjob -ne $null) { $wbjob | select-object starttime, endtime, 
                                                      hresult, errordescription }
       else                  { "No backups for $env:COMPUTERNAME" }
     }
   } catch { "Failed to connect to $Server" }
 }

$output | 
 Sort-Object PSComputerName | 
 Format-Table -Auto PSComputerName, HResult, ErrorDescription, StartTime, EndTime | 
 Out-File c:\scripts\results.txt

EDIT: Code change (see below)

How To Ask Questions The Smart Way

message edited by Razor2.3


Report •

#2
April 10, 2017 at 10:30:33
Thanks - that works. One odd thing though. I have a machine that has no backup job but is accessible and it shows in the file twice - no backup jobs and failed to connect.

Report •

#3
April 10, 2017 at 12:08:37
I don't have experience with Windows' backup past WinNT 4, so I'm unsure of the behavior of Get-WBJob. If it's erroring out on you, you'll need to handle that as well. Easiest way would probably be to add '-ErrorAction SilentlyContinue' to the Get-WBJob line, but I don't know all of the situations where Get-WBJob can error out.

How To Ask Questions The Smart Way


Report •
Related Solutions


Ask Question