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"
}
相信未来 - 该面对的绝不逃避,该执著的永不怨悔,该舍弃的不再留念,该珍惜的好好把握。