如何在 Powershell 中处理多个自定义 "Catch" 错误消息?

How to handle multiple custom "Catch" error messages in Powershell?

我在一个 Try 中有 3 个命令,我想为每个命令自定义 Catch 错误消息,以防出现错误

例如如果第一个失败,那么我想收到以下消息:“创建目录时出错!”

如果第二次失败则:“复制项目失败”

如果第三个失败则:“未创建内容”

我该如何应用?

    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?"
    } 

感谢您的帮助。

zett42给出的答案是正确的。以下是您将如何在您的解决方案中实施它:

$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: $_"
} 

输出例如是:

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

我添加了 ErrorAction 以确保它在执行后立即停止每个错误。