在 PowerShell 中尝试 catch 仍然显示错误

问题描述 投票:0回答:1

这是我的代码:

try {
    $usernames = Get-LocalUser | Where-Object { $_.enabled -EQ 'True' } | Select-Object 'Name'
    $usernames | ForEach-Object { 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 从未运行。有什么问题吗?

powershell error-handling
1个回答
4
投票

如评论中所述,您可以使用

-ErrorAction Stop
,以便 PowerShell 将错误视为终止错误,这样错误将被您的
try
捕获。

关于如何更改脚本的逻辑,以便它可以捕获错误但也不会停止进一步处理。为此,您只需将

try / catch
语句放入循环内:

Get-LocalUser | Where-Object Enabled | ForEach-Object {
    try {
        $addLocalGroupMemberSplat = @{
            Group       = 'Hyper-V Administrators'
            Member      = $_
            ErrorAction = 'Stop'
        }

        Add-LocalGroupMember @addLocalGroupMemberSplat
    }
    catch {
        Write-Error -Message 'Failed to add user' -Exception $_.Exception
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.