在PowerShell中终止错误不会停止函数执行

问题描述

我正在编写的函数中有以下代码段,用于检查目录是否可被当前用户写入:

  # Write temp file to see if we can
  $checkPermArgs = @{
    Path = $tempFilePath
    ErrorAction = 'SilentlyContinue'
    ErrorVariable = 'wError'
  }
  Write-Verbose "Writing file ${tempFilePath}"
  "$($MyInvocation.MyCommand) check $([DateTime]::Now)" | Out-File @checkPermArgs
  
  # Check for any errors
  if( $wError ) {
    return $false
  } else {
    $true
  }

我的理解是IOException应该是一个终止错误,但是由于某种原因,我将继续执行我的函数。如果我尝试写$tempFilePath并得到IOException,而不是终止我的函数,它会继续执行并评估if( $wError )语句,并在控制台中返回并显示$false,产生以下输出

Out-File: 
Line |
  34 |  … cation.MyCommand) check $([DateTime]::Now)" | Out-File @checkPermArgs
     |                                                  ~~~~~~~~~~~~~~~~~~~~~~~
     | Access to the path '/path/to/tempFile.txt' is denied.
False

由于目标是仍然处理错误不显示给最终用户,所以我意识到我对Out-File进行了愚弄并将其包装在try/catch块中,但是我很好奇为什么会出现终止错误这里实际上并没有终止函数的执行。

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)