PowerShell - Error Handling

PowerShell - Error Handling

Understanding Error Variable in detail to use it efficiently

$error.GetType()

$error[0]
Test

$error[0].Exception.GetType().fullname

#Microsoft.PowerShell.Commands.GroupNotFoundException

Test-Connection fakehost

$error[0].Exception.GetType().fullname

$error|Get-Member|ft name, membertype

$error[0].InvocationInfo
$error[0].InvocationInfo.Line
$error[0].InvocationInfo.PositionMessage

$error.Clear()

$error

Try-Catch-Finally

Try {
$UserToKeep = Get-Content C:\Users\Administrator\Desktop\UsersToKeep.txt -ErrorAction Stop

$GroupMembers = Get-LocalGroupMember -Group DBAccess

foreach ($member in $GroupMembers)
{
if ($UserToKeep -notcontains $member)
{Remove-LocalGroupMember -Group DBAccess -Member $Member;
Write-Host "$Member removed from Group" -BackgroundColor Red}
}
}
Catch {
Write-Host "`nError Message:" $_.exception.Message
}
Finally {
Write-Host "This is done"
}
posted @ 2022-02-10 22:04  晨风_Eric  阅读(41)  评论(0编辑  收藏  举报