I am having some problems with handling errors/exceptions regarding the invoke-command.
I am trying to catch errors when the target computer does not exist, however the message i am shown and the way the script in the catch block acts makes me think there is something i missed or miss understood.
this is the portion of the script with the problem:
$session = New-Pssession -computername $computerName
Invoke-Command -session $session -ScriptBlock $command -ArgumentList $sqlServerName, $userToGivePermisions
Remove-PSsession -session $session
Basically i want to handle errors when $computerName
is not a valid computer on the network. I purposely gave it a wrong name to test it out and i get the following error:
[dcd] Connecting to remote server failed with the following error message : WinRM cannot process the request. The following error occured while using Kerberos authentication: The network path was not found.
Possible causes are:
-The user name or password specified are invalid.
-Kerberos is used when no authentication method and no user name are specified.
-Kerberos accepts domain user names, but not local user names.
-The Service Principal Name (SPN) for the remote computer name and port does not exist.
-The client and remote computers are in different domains and there is no trust between the two domains.
After checking for the above issues, try the following:
-Check the Event Viewer for events related to authentication.
-Change the authentication method; add the destination computer to the WinRM TrustedHosts configuration setting or use HTTPS transport.
Note that computers in the TrustedHosts list might not be authenticated.
-For more information about WinRM configuration, run the following command: winrm help config. For more information, see the about_Remote_Troubleshooting Help topic.
+ CategoryInfo : OpenError: (System.Manageme....RemoteRunspace:RemoteRunspace) [], PSRemotingTransportException
+ FullyQualifiedErrorId : PSSessionOpenFailed
[dcd] is the name of the non existing machine. I put the code in a try catch and did a check on the error message using a -contains
. The condition ALWAYS came out false and i tried almost ever single word in the error above.
When i displayed the error message in the catch block using $_.exception.message
i got a different error about $session being null.
When i did a -contains
using words in the displayed error message about $session it still returned false for every word i tested.
I don't understand which of these is the error and why isn't the -contains
ever returning true. I added the -ea stop
to all 3 lines to catch all the non terminating errors but to no avail.
Anyone have any idea what is going on?
-contains
checks whether an element is in an array or not. e.g:
1,2,3 -contains 2 # Is True
"a","bc","d" -contains "b" # Is False
Try the -match
or the -like
operators instead. Have a look at the comparison operator documentation.