The desired result from this script is to find out the PowerShell version on a list of hosts. I would like to handle the exception when the remote machine is down or does not have remoting enabled. However, the catch
does not appear to be entered. Just the standard red flaming error message from PowerShell appears.
What do I need to do to catch the exception?
X:\Scripts\PSAutomation> Get-Content .\get-versions.ps1
server_list = @(
'CAPPY'
)
$server_list |
ForEach-Object {
Try {
Invoke-Command -ComputerName $_ {$PSVersionTable.PSVersion}
}
Catch
{
Write-Host "Failed to connect to $_"
}
}
X:\Scripts\PSAutomation> .\get-versions.ps1
[CAPPY] Connecting to remote server CAPPY failed with the following error message : WinRM cannot process the
request. The following error occurred while using Kerberos authentication: Cannot find the computer CAPPY. Verify
that the computer exists on the network and that the name provided is spelled correctly. For more information, see
the about_Remote_Troubleshooting Help topic.
+ CategoryInfo : OpenError: (CAPPY:String) [], PSRemotingTransportException
+ FullyQualifiedErrorId : NetworkPathNotFound,PSSessionStateBroken
Just set the ErrorAction
for that call to stop
:
Invoke-Command -ComputerName "sdf" {$PSVersionTable.PSVersion} -ErrorAction Stop