【问题标题】:Powershell-else in try/catch尝试/捕获中的 Powershell-else
【发布时间】:2019-04-17 03:46:34
【问题描述】:

get-addomain 成功时,我正在尝试写入输出。

Try/catch 仅在命令失败时写入输出

try {

get-addomain -Identity  d.contoso.com  

}

catch {

Write-Output "failed"

}

我尝试了以下操作:

if (-not (get-addomain -Identity  d.contoso.com))
{
return "failed"
}

else

{
write-output "ok"
}

If (get-addomain -Identity  d.contoso.com  )
{
    Write-Output "ok"
}
Else
{
    write-output "failed"
}

但在这两种情况下都得到了

get-addomain : Cannot find an object with identity: 'd.contoso.com' under: 'DC=ad,DC=contoso,DC=com'.

【问题讨论】:

    标签: powershell error-handling try-catch


    【解决方案1】:

    tryblock 一直运行,直到抛出错误。如果get-addomain 没有以错误结束,try-case 将运行{} 中编写的以下命令。

    所以一种方法是在没有抛出错误的情况下说输出正常:

    try {
      get-addomain -Identity  d.contoso.com  
      Write-Output "ok"
    }
    
    catch {
      Write-Output "failed"
    }
    

    但是如果您想仔细检查,您仍然可以在try-catch 中进行if 检查:

    try {
      If (get-addomain -Identity  d.contoso.com  )
      {
          Write-Output "ok"
      }
      Else
      {
        write-output "failed"
      }
    }
    catch {
      Write-Output "failed"
    }
    

    【讨论】:

    • 第二个解决方案有效!!,谢谢,如果我指定第一个也有效 |出空
    【解决方案2】:
    try{
        $domain = Get-ADDomain -Identity d.contoso.com
        Write-Output $domain
    }catch{
        Write-Output "Failed with message '$($_.Exception.Message)'"
    }
    

    当您使用 AD CmdLets 时,如果指定了不存在的标识,它会失败。因此,如果您搜索的对象不存在,您将最终陷入困境。如果您希望输出AD域信息,您编写的第一段代码实际上是正确的。

    【讨论】:

      猜你喜欢
      • 2018-01-10
      • 2016-11-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-09-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多