【问题标题】:Powershell Try&Catch Run multiple commands inside tryPowershell Try&Catch 在 try 中运行多个命令
【发布时间】:2013-05-08 19:12:44
【问题描述】:

您好,我正在尝试弄清楚如何做到这一点或其他方式

try {
Get-ADComputer -Identity namedoesnotexist
(Get-ChildItem).FullName
}
catch {$_ | Out-File log.log}

运行此代码时,我使用的名称不存在,因此出现错误,catch 会将其写入我的日志文件(仅作为示例) 我想要完成的是错误被捕获,但 try 语句继续运行我的 Get-Childitem 命令并尝试它。 还有其他简单的方法吗?

【问题讨论】:

    标签: powershell try-catch powershell-2.0


    【解决方案1】:

    在 try..catch 中只放一行就可以达到这种效果

    try 
    {
      Get-ADComputer -Identity namedoesnotexist
    }
    catch 
    {
      $_ | Out-File log.log
    }
    (Get-ChildItem).FullName
    

    但也许 trap 是您正在寻找的东西

    trap
    {
      $_ | Out-File log.log
      continue # remove this if you still want to see each error
    }
    Get-ADComputer -Identity namedoesnotexist
    (Get-ChildItem).FullName
    

    【讨论】:

    • Out-File 使用-Append 开关,这样您就不会覆盖每个错误的日志文件。
    • trap 正是我想要的。谢谢!
    猜你喜欢
    • 2015-12-07
    • 2013-11-25
    • 2014-03-27
    • 2012-11-16
    • 1970-01-01
    • 1970-01-01
    • 2017-05-01
    • 1970-01-01
    • 2020-04-02
    相关资源
    最近更新 更多