这是我的代码:
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 从未运行。有什么问题吗?
-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
}
}