【问题标题】:Outputting Error using Try/Catch [duplicate]使用 Try/Catch 输出错误 [重复]
【发布时间】:2017-11-25 18:34:57
【问题描述】:

我正在编写一个可以从外部文本文件中删除文件的脚本。该脚本运行良好,但现在,我想通过将错误输出到外部文本文件来改进它。

我尝试过 try and catch 但我不知道为什么它不起作用。这是相关的ps1代码:

$LogFile   = "log.txt" 
$ErrorFile = "error.txt"

Get-ChildItem -Path (Get-Content liste.txt) |
    ft FullName -HideTableHeaders |
    Out-File $logfile -Append

foreach ($i in Get-Content liste.txt) {
    try {
        Get-ChildItem -Path $i -Include *.* -Recurse | Remove-Item
        Write-Output "tout est supprimé"
    } catch {
        Write-Output "Something's wrong" 
    }
}

【问题讨论】:

  • 您错误地使用了 Try/Catch 块。除非在 finally 块中,否则在 catch 之后不应有代码。
  • 即使我在 catch 后删除了代码,脚本仍然有效,但只有我尝试的消息出现,即使有错误

标签: powershell error-handling try-catch


【解决方案1】:

您需要通过get-childitem添加-ErrorAction Stop

【讨论】:

  • 谢谢!!它完美地工作。但是现在,如果我想捕获诸如“权限被拒绝”(IOException)之类的非终止错误,它不起作用并且出现成功消息。我知道 try/catch 无法捕获非终止错误,但是否还有显示错误的解决方案?
猜你喜欢
  • 2023-03-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-10-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多