Home > Software engineering >  How to handle multiple custom "Catch" error messages in Powershell?
How to handle multiple custom "Catch" error messages in Powershell?

Time:02-10

I have 3 commands inside of a Try and I want custom Catch error messages for each of them in case of an error

e.g. If the first will fail then I would like to get the following message: "Error creating a directory!"

If the second will fail then: "Copy items failed"

If the third will fail then: "Content is not created"

How can I apply that?

    Try{

        New-Item -ItemType Directory -Name "Script" -Path "C:\Temp\" -Force

        Copy-Item -Path $FilePath_ps1 -Destination C:\temp\script -Force

        Set-Content -Value "test" -Path "C:\Temp\Script\test.txt" -Force
    
    }
    Catch{
        " what code do I need here?"
    } 

Thanks for your help.

CodePudding user response:

The answer zett42 gave is correct. Here is how you would implement it in your solution:

$errorAction = "STOP"
Try{
    $errorMsg = "New-Item failed"
    New-Item -ItemType Directory -Name "Script" -Path "C:\Temp\" -Force -ErrorAction $errorAction
    $errorMsg = "Copy-Item failed"
    Copy-Item -Path $FilePath_ps1 -Destination C:\temp\script -Force -ErrorAction $errorAction
    $errorMsg = "Set-Content failed"
    Set-Content -Value "test" -Path "C:\Temp\Script\test.txt" -Force -ErrorAction $errorAction
}Catch{
    $errorMsg   " with error: $_"
} 

The output would be for instance:

Copy-Item failed with error: Cannot bind argument to parameter 'Path' because it is null.

I have added the ErrorAction to make sure it stops on every error right after the execution.

  • Related