2

我想知道Try / Catch以下是否有效,或者我应该使用 anIF ($problem)而不是Try/Catch

Try {
    New-Item -Path C:\reports -ItemType Directory -ErrorAction SilentlyContinue -ErrorVariable Problem -Force
}
Catch {
    Write-Warning "Problem with C:\Report directory. Unable to create report $Type of $SourceEmail $Flag $DestinationEmail"
}

我正在检查目录是否存在,如果不存在则尝试创建目录。我不确定是否因为我使用-ErrorAction SilentlyContinue -ErrorVariable Problemtry/catch没有按预期工作?

替代品

 New-Item -Path C:\reports -ItemType Directory -ErrorAction SilentlyContinue -ErrorVariable Problem -Force
 If ($Problem) {
  Write-Warning "Problem trying to create C:\Reports."
 }
4

1 回答 1

5

我正在检查目录是否存在,如果不存在则尝试创建目录。

New-Item-Force开关可以用来创建一个目录,除非它已经存在;返回一个System.IO.DirectoryInfo描述预先存在的目录或新创建的目录的对象(请注意,它-Force也会根据需要创建目录)。

由于您已经在使用-Force,这意味着只报告真正的错误情况,例如缺少权限。

在最简单的情况下,您可以在发生此类错误情况时简单地中止-ErrorAction Stop脚本,使用将报告的(第一个)非终止错误转换New-Item脚本终止错误:

$targetDir = New-Item -Force -ErrorAction Stop -Path C:\reports -ItemType Directory 

如果发生错误,它将被打印,并且脚本将被中止。

如果您想捕获错误并执行自定义操作,您有两个相互排斥的选项:

  • $Problem捕获变量, via中的非终止错误-ErrorVariable Problem,然后作用于 的值$Problem-ErrorAction SilentlyContinue禁止显示错误:[1]
$targetDir = New-Item -Force -ErrorAction SilentlyContinue -ErrorVariable Problem -Path C:\reports -ItemType Directory

if ($Problem) { 
  Write-Warning "Problem trying to create C:\Reports: $Problem"
  # Exit here, if needed.
  exit 1
}
  • 将(第一个)非终止错误提升为脚本终止一个 via-ErrorAction Stop并使用try { ... } catch { ... }语句来捕获它,其中的catch$_指的是手头的错误:
try {
  $targetDir = New-Item -Force -ErrorAction Stop -Path C:\reports -ItemType Directory
} catch {
  $Problem = $_
  Write-Warning "Problem trying to create C:\Reports: $Problem"
  # Exit here, if needed.
  exit 1
}

有关 PowerShell 异常复杂的错误处理的全面概述,请参阅此 GitHub 文档问题


[1] 这使得通过-ErrorVariable静默捕获错误;不要使用,因为那样-ErrorAction Ignore-ErrorVariable失效。

于 2021-10-05T17:17:29.740 回答