mardi 27 juillet 2021

Powershell: Add users to a group with if-else statement

I'm learning Powershell scripting on a Windows Server. I'm adding users by importing their data from a csv file. The users & their info get added correctly.

The problem is my powershell script has to auto-add new users to groups based on their Departments. The if-else statements I use are in a for-loop. With my current code, all new users get added to the IT group only, even if they're not in the IT Department. They don't get added to any other group. Any advice?

Import-Module ActiveDirectory
$Users = Import-CSV -Path "C:\Users\Administrator\Desktop\Users.csv"

foreach ($User in $Users){
    $uname = $User.Username
    $first = $User.Firstname
    $last = $User.Lastname

    if ( Get-ADUser -Filter {SamAccountName -eq $uname})
    {
        Write-Warning "The user $uname already exists."
    }
    else
    {
        New-ADUser `
        -Name "$first $last" `
        -SamAccountName $uname `
        -Path $User.OUPath `
        -Office $User.Office `
        -Department $User.Department `
        -Enabled $true

        if (Get-ADUser -Filter {Department -eq "IT"})
        {
                Add-ADGroupMember -Identity IT -Members $uname
        }
        elseif (Get-ADUser -Filter {Department -eq "Marketing"})
        {
                Add-ADGroupMember -Identity Marketing -Members $uname
        }
        elseif (Get-ADUser -Filter {Department -eq "Sales"})
        {
                Add-ADGroupMember -Identity Sales -Members $uname
        }
        else
        {
               Add-ADGroupMember -Identity HR -Members $uname
        }
    }  #close of first else loop
} #close of foreach loop```


Aucun commentaire:

Enregistrer un commentaire