Problems with catch in PowerShell
powershell
Solution
Try catching `System.Management.Automation.RuntimeException` instead of `System.InvalidOperationException`.
Try
{
Add-Computer -DomainName "MyDomain.Dom" -Credential $DomainCred
}
Catch [System.Management.Automation.RuntimeException]
{
'Error: {0}' -f $_.Exception.Message
}
Problem
I have a problem with the catch command. I have the following script I'm trying to process: ``` 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: ``` 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): ``` Try { Add-Computer -DomainName "MyDomain.Dom" -Credential $DomainCred -PassThru -ErrorAction Stop } Catch [System.Management.Automation.RuntimeException] { "Your computer is unable to contact the domain" } ```