Author Posts

May 22, 2017 at 1:09 pm

Hello!

I have a simple If/Else as part of a ForEach-Object loop...

$newStaff | ForEach-Object {

                Add-ADGroupMember "Staff 8e6" $newStaff.UserLogonName 
                
                if ($_.CertifiedJob -eq '0' ) {Add-ADGroupMember "CLASSIFIED STAFF" $newStaff.UserLogonName}
                
                Else {Add-ADGroupMember "CERTIFICATED STAFF" $newStaff.UserLogonName}
                                    
                }

You can see, if $_.CertifiedJob -eq '0' (0 is a STRING), I want the user to be added to a group.

If $_.CertifiedJob -eq '-1' (again, a string), I want the user added to a different group.

I have tried, If ($_.Certifiedjob -like '*0*'), etc.

Right now, it is just adding the user to both AD groups in the statement.

I have been looking at the statement and the input and just cannot see why this is happening.

$newStaff = Import-CSV mycsv.csv, which it includes a column called 'CertifiedJob' which will always be a string, either '0' or '-1'.

Thank you

May 22, 2017 at 1:23 pm

You shouldn't be using $NewStaff inside your function.. you should be using $_, and preferably (imho) assigning the value you want to an internal variable, so as not to have the $_ get changed and supply the incorrect information.

$newStaff | ForEach-Object {
                $LogonName = $_.UserLogonName
                Add-ADGroupMember "Staff 8e6" $LogonName
                if ($_.CertifiedJob -eq '0' ) {Add-ADGroupMember "CLASSIFIED STAFF" $LogonName}
                Else {Add-ADGroupMember "CERTIFICATED STAFF" $LogonName}
                }

Using the $NewStaff collection, you are telling each of your Add-ADGroupMember commands to add the entire collection.

David F.

May 22, 2017 at 1:35 pm

David,

This helped! Thank you very much. Oversight on my part. I was using $_. in a couple of loops above this one, and just missed that completely.

Reading your answer I understand what was happening.

Thank you!