在PowerShell中尝试捕获仍显示错误

axzmvihb  于 2022-11-10  发布在  Shell
关注(0)|答案(1)|浏览(167)

这是我的代码:

try {
$usernames = Get-LocalUser | ?{$_.enabled -EQ "True"} | select "Name"
$usernames | foreach { Add-LocalGroupMember -Group "Hyper-V Administrators" -Member $_.Name }
}
catch
{write-host "All user accounts are already part of the Hyper-V Administrators group `n" -ForegroundColor black -BackgroundColor yellow}

当我运行它时,我仍然在控制台中看到错误,Catch从未运行过。有什么问题吗?

hfyxw5xn

hfyxw5xn1#

正如注解中所述,您可以使用-ErrorAction Stop,以便PowerShell将错误视为终止错误,这样错误将被您的try block捕获。
关于如何更改脚本的逻辑,以便它可以捕获错误,但也不会停止进一步的处理。为此,您只需将try / catch语句放入循环中:

(Get-LocalUser | ? Enabled).Name | ForEach-Object {
    try {
        Add-LocalGroupMember -Group "Hyper-V Administrators" -Member $_ -ErrorAction Stop
    }
    catch {
        Write-Error -Message 'Failed to add user' -Exception $_.Exception
    }
}

相关问题