gpt4 book ai didi

azure - Powershell - 将 cmd-let 错误捕获到变量

转载 作者:行者123 更新时间:2023-12-03 02:41:51 27 4
gpt4 key购买 nike

我正在尝试将命令中的错误捕获到变量中,并在发生错误时退出脚本

Add-DistributionGroupMember -Identity <a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="1f507979767c7a5f7a677e726f737a317c7072" rel="noreferrer noopener nofollow">[email protected]</a> -Member `
<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="fb8f949582d5888f9a8990bb9e839a968b979ed5989496" rel="noreferrer noopener nofollow">[email protected]</a> -ErrorAction stop -ErrorVariable MyError `
if ($MyError.Count -gt 0) {`
exit

}

但是 MyError 变量为空并且脚本继续运行,

但是,如果指定-ErrorAction SilentlyContinue,则脚本将继续,并且错误变量为空

最佳答案

正如评论中已经提到的,您应该对指定的 cmdlet 使用嵌套的 try catch block ,如下所示:

try
{
Add-DistributionGroupMember -Identity <a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="fdb29b9b949e98bd98859c908d9198d39e9290" rel="noreferrer noopener nofollow">[email protected]</a> -Member `
<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="94e0fbfaedbae7e0f5e6ffd4f1ecf5f9e4f8f1baf7fbf9" rel="noreferrer noopener nofollow">[email protected]</a> -ErrorAction stop -ErrorVariable MyError `
}
catch {
if($MyError.Count -gt 0)
{
Write-Output $myerror

#if you want to exit execution after this error, use exit command as blow
exit
}
}

关于azure - Powershell - 将 cmd-let 错误捕获到变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60888980/

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