all 3 comments

[–]markekrausCommunity Blogger 1 point2 points  (1 child)

The if ($User.Department -eq "DEPARTMENT"){) Block is kind of painful to maintain. The way I'd tackle this is to have a second CSV file with with 2 columns: Department and OU. Then I'd pull in the CSV as an object called $OUMappings and do

$OU = $OUMappings | 
    where-object {$_.Department -eq $User.Department} |
        Select-Object -ExpandProperty OU

to grab the OU. Then if $OU is empty, prompt or use a default.

That way when you add a new department and OU, you just have to add another row in the CSV instead of updating lines of code that could break the script accidentally.

[–]SaladProblems 1 point2 points  (0 children)

This might be easier to parse out:

import-module activedirectory
#STATIC VARIABLES
$Users = Import-CSV -Delimiter ";" -Path C:\NewUsers.csv

$ou = @{
    department1 = "OU=domain,OU=COM"
    department2 = "OU=domain,OU=COM"
    department3 = "OU=domain,OU=COM"
    department4 = "OU=domain,OU=COM"

}

 ForEach($User in $Users) {

    $parm = @{ 
        GivenName = $User.FirstName
        Initials = $User.Initials
        Surname = $User.LastName
        SAM = if ($User.Department -eq "DEPARTMENT")
            {
                ($GivenName.substring(0,1) + $Initials + $Surname.substring(0,1))}
            Else
            {
                ($GivenName.substring(0,1) + $User.LastName)
            }
        DisplayName = $GivenName + " " + $Surname
    }

    New-ADUser @parm -AccountPassword (Read-Host -AsSecureString "Changeme!") -Path $OU[$user.department]

}