gpt4 book ai didi

powershell - 在try/catch中使用Powershell-else

转载 作者:行者123 更新时间:2023-12-03 08:10:28 26 4
gpt4 key购买 nike

我尝试在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'.

最佳答案

try块运行,直到引发错误为止。如果get-addomain没有以错误结尾,则try-case将运行{}内编写的以下命令。

因此,一种方法是仅在没有错误抛出的情况下说输出正常:

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

catch {
Write-Output "failed"
}

但是,如果您想再次检查,仍然可以在 if中进行 try-catch检查:
try {
If (get-addomain -Identity d.contoso.com )
{
Write-Output "ok"
}
Else
{
write-output "failed"
}
}
catch {
Write-Output "failed"
}

关于powershell - 在try/catch中使用Powershell-else,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53295762/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com