looking for a hint of how I would do a count process in a try / catch block.
my situation is im running a try block with get-aduser against a csv file. then doing a catch with the Microsoft.ActiveDirectory.Management.ADIdentityNotFoundException
I would like to count how many of those exceptions happen so I have a way of telling if there were none… which would tell me all users on the csv are actual valid users.
is this even possible? im doing a search and having a hard time finding anything…
im doing a for-each. $varB shows 1, but only if I run “$varb” manually after script runs. “$varA” shows 0, again… only if I run it manually after script runs.
same thing if I rem out the out-null… is it because of the -erroraction stop? if so… but don’t I need that to catch the exception?
foreach ($line in $userlist) {
$varA = 0
$varB = 0
try {
Get-ADUser $line.ID -ea stop # | out-null # (out-null suppresses output, so only none existant users are displayed)-MG
$varB++
}
catch [Microsoft.ActiveDirectory.Management.ADIdentityNotFoundException] {
$varA++
" $line.ID doesn't exist.....beginning creation of user " # | out-file "c:\scripts\feedback\HS-Student-Creation.txt" -Append
write "$varA errors caught"
write "$varB user accounts checked" }
}
Well… that’s a scope thing. Variables defined inside a script stop existing when the script finishes. So if you’re checking “after the script runs,” then I wouldn’t expect anything to have a value. You’ve also got a logic error.
Your two Write statements are going to run every tie you hit an error… so if your last account exists, you won’t see that output.
$varA = 0
$varB = 0
foreach ($line in $userlist) {
try {
Get-ADUser $line.ID -ea stop # | out-null # (out-null suppresses output, so only none existant users are displayed)-MG
$varB++
} #try
catch [Microsoft.ActiveDirectory.Management.ADIdentityNotFoundException] {
$varA++
" $line.ID doesn't exist…..beginning creation of user " # | out-file "c:\scripts\feedback\HS-Student-Creation.txt" -Append
} #catch
} #foreach
write "$varA errors caught"
write "$varB user accounts checked"
Try moving the write statements to the end of the script, just after closing the ForEach loop. You also need to move the two initial set-to-zero statements. Look at your logic - $varA and $varB are set to zero EACH TIME you hit a new user. So they’re never going to be more than 1, because you’re resetting them to zero each time.
Personally, I’d also use better variable names - $UsersChecked and $UsersFailed for example. Makes the script easier to read.
oh man… I feel so stupid I didn’t realize that logic. both the variable and the write command in a loop. thanks for pointing that out to me… .and I agree with
the naming… I usually do make more meaningful names… but while trying to work out the logic I tend to use quick little variable names for testing purposes.
but it would actually be useful to use a meaningful name to cut back on confusion during the beginning stages of the script.