在try / catch中使用Powershell-else

时间:2018-11-14 08:23:30

标签: powershell error-handling try-catch

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'.

2 个答案:

答案 0 :(得分:1)

The tryblock runs until a error is getting thrown. If get-addomain doesn't end with an error, the try-case will run the following commands written inside the {}.

So one way would be to just say the output is ok if no error gets thrown:

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

catch {
  Write-Output "failed"
}

But if you want to double check, you can still do the if check in the try-catch:

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

答案 1 :(得分:0)

try{
    $domain = Get-ADDomain -Identity d.contoso.com
    Write-Output $domain
}catch{
    Write-Output "Failed with message '$($_.Exception.Message)'"
}

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