Question:
I have a problem with the catch command. I have the following script I’m trying to process:
1 2 3 4 5 6 7 8 9 10 |
Try { Add-Computer -DomainName "MyDomain.Dom" -Credential $DomainCred -PassThru -ErrorAction Stop } Catch [System.InvalidOperationException] { "Your computer is unable to contact the domain" } |
Every time I run this though I am not getting anything in the catch block. Here is the error reported that I get from the script:
1 2 3 4 5 6 7 8 9 10 |
PSMessageDetails : Exception : System.InvalidOperationException: This command cannot be executed on target computer('') due to following error: The specified domain either does not exist or could not be contacted. TargetObject : CategoryInfo : InvalidOperation: (MYPC:String) [Add-Computer], InvalidOperationException FullyQualifiedErrorId : InvalidOperationException,Microsoft.PowerShell.Commands.AddComputerCommand ErrorDetails : InvocationInfo : System.Management.Automation.InvocationInfo PipelineIterationInfo : {0, 1} |
Any ideas?
A working solution (thanks to PK and Patrick for their combined contributions):
1 2 3 4 5 6 7 8 9 10 |
Try { Add-Computer -DomainName "MyDomain.Dom" -Credential $DomainCred -PassThru -ErrorAction Stop } Catch [System.Management.Automation.RuntimeException] { "Your computer is unable to contact the domain" } |
Answer:
Try catching System.Management.Automation.RuntimeException
instead of System.InvalidOperationException
.
1 2 3 4 5 6 7 8 9 10 |
Try { Add-Computer -DomainName "MyDomain.Dom" -Credential $DomainCred } Catch [System.Management.Automation.RuntimeException] { 'Error: {0}' -f $_.Exception.Message } |