【问题标题】:Why is my try catch error passing as successful even with -ErrorAction Stop on?为什么即使打开 -ErrorAction Stop,我的 try catch 错误也会成功传递?
【发布时间】:2019-06-28 07:15:35
【问题描述】:

下面是一个简单的Try Catch,但是当我测试它时,它似乎成功归档,所以我在变量中包含了一个不存在的位置来测试失败,但奇怪的是,即使失败出现在 ISE 窗口中输出仍然显示成功,因为下面的某些事情不太对劲,任何想法都是我迷失在哪里出了问题。

## The location/filename where the Logs will be stored
$varfullpath = "I:\Dev\BI\Reference Data\Release_Event_log.txt"       
## The location/filename of the Source to copy from                                    
$sourceDirectory  = "C:\Users\Simon.Evans\Documents\Source Data\kljhkjlOS\"
## The location/filename of the Destination to copy to  
$destinationDirectory = "I:\Dev\BI\Projects\Powershell\Test Area\Source Data\OkjhkhDS\"
$Server = "CHH-BITEST"
$CurrentDate = Get-Date
try{
    Get-ChildItem -Path $sourceDirectory -File -Filter "*.csv" | Copy-Item -Destination $destinationDirectory -ErrorAction Stop
    Write-Log -Message "Copy from $sourceDirectory to $destinationDirectory suceeded"  -path $varfullpath             
}
catch{
    $Error[0] | Write-Log -path $varfullpath                                                                            
    Write-log -Message "Copy from $sourceDirectory to $destinationDirectory Failed"  -Level Error -path $varfullpath     
} 

Start-Process notepad $varfullpath  ## Opens the file immediately for review

【问题讨论】:

    标签: powershell try-catch


    【解决方案1】:

    get-childitemcommand 抛出错误。

    像这样将 -ErrorAction Stop 添加到这个命令中:

    Get-ChildItem -Path $sourceDirectory -File -Filter "*.csv" -ErrorAction Stop | Copy-Item -Destination $destinationDirectory -ErrorAction Stop

    【讨论】:

      【解决方案2】:

      @guiwhatsthat's answer 的一些补充:

      PowerShell 区分终止错误和非终止错误。借助常见的 ErrorAction 参数,您可以设置 cmdlet 在发生此类错误时的行为。如果您想更改多个 cmdlet 或脚本中的部分的行为,您可以更改 $ErrorActionPreference 的值。

      来自PowerShell documentation

      $ErrorActionPreference

      确定 PowerShell 如何响应命令行或脚本、cmdlet 或提供程序中的非终止错误(不会停止 cmdlet 处理的错误),例如由 Write-Error cmdlet 生成的错误。

      您还可以使用 cmdlet 的 ErrorAction 通用参数来覆盖特定命令的首选项。

      有效值:

      停止:显示错误信息并停止执行。

      查询:显示错误消息并询问您是否要继续。

      继续:显示错误消息并继续(默认)执行。

      暂停:自动暂停工作流作业以进行进一步调查。排查后,可以恢复工作流程。

      静默继续:没有效果。不显示错误消息,继续执行而不会中断。

      【讨论】:

        猜你喜欢
        • 2017-03-24
        • 2021-06-10
        • 2015-02-15
        • 2021-06-19
        • 2017-10-17
        • 1970-01-01
        • 2013-12-12
        • 2019-05-29
        • 2016-01-27
        相关资源
        最近更新 更多