If Else is accepting both conditions

This topic contains 2 replies, has 2 voices, and was last updated by  camelCreed 1 year ago.

  • Author
  • #71189



    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

  • #71194


    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.

    • #71197



      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!

You must be logged in to reply to this topic.