I have a ps script (in a est environment with fake user names!) that adds random users to a security group if they´re NOT already in that group. Now I want to count the successfully added users (lines with “added to testEx”) in each iteration…
adding 5 users to testEx
tfeichtner Truman Feichtner added to testEx
bfigeroa Figeroa Bernardo added to testEx
fsaylors Saylors Fatima already in testEx
mrhymes Micaela Rhymes added to testEx
mlayous Ma Layous added to testEx
0 users have been added to testEx
The last line should read “4 users have been added to testEx”.
I already tried different variations of count and measure, to no avail… any ideas???
btw, this is the code:
$adUsers = Get-ADUser -Filter {enabled -eq $True} -SearchBase $ouPath | Select-Object -Property SamAccountName,Name | Get-Random -Count $rCount
ForEach ($adUser in $adUsers) {
$user = Get-ADGroupMember -Identity $secGroupName | Where-Object {$_.name -eq $adUser}
$saName = $adUser.SamAccountName
$saNamePad = ($adUser.SamAccountName.PadRight(15))
$uNamePad = ($adUser.Name.PadRight(20))
# check if user already member of security group "testEx"
# Retrieve AD user group membership
$ExistingGroups = Get-ADPrincipalGroupMembership $adUser.SamAccountName | Select-Object Name
If ($ExistingGroups.Name -eq $secGroupName) {
Write-Host $saNamePad $uNamePad " `t already in" $secGroupName -ForeGroundColor Yellow
}
Else {
# add random users to secGroup
$uCount = $(Add-ADGroupMember -Identity $secGroupName -Members $saName | Measure).Count
Write-Host $saNamePad $uNamePad -NoNewLine -ForegroundColor Cyan; Write-Host " `t added to" $secGroupName -ForeGroundColor Green
}
}
# count added users
$uCountPad = "$uCount".PadLeft(3)
Write-Host $uCountPad " users have been added to" $secGroupName
That sounds like a weird task. Is it for practicing purposes?
May I suggest another approach? After collecting a random number of users I’d determine wich of these users are not yet in the group. You can easily do this with Compare-Object. This way you have the count you’re after and don’t need to test all users individually if they are already members of the group.