I am using a switch statement with an import of a CSV in a Foreach loop. I am not sure what I am doing wrong. Within the csv I have a column called company which will provide a 4 digit number example of this 9020. In my switch statement depending on what company you are from it will or should place you in a particular OU in AD. The code below is what I am working with in my test lab.
$ADUsers = Import-Csv C:\Powershell\New_User.csv
Foreach ($User in $ADUsers) {
$Username = $User.SamAccountName
$Password = $User.password
$Firstname = $User.firstname
$Lastname = $User.lastname
$Description = $User.Description
#$OU = $User.OU
#$email = $User.email
#$streetaddress = $User.streetaddress
#$city = $User.city
#$zipcode = $User.zipcode
$state = "FL"
#$country = $User.country
#$telephone = $User.telephone
$jobtitle = "Staff"
$company = $User.company
#$department = $User.company
#region cc
Switch ( $Company ) {
9030 {
$Department = "9030 Transportation"
$ADDept = "OU=Staff,OU=Transportation 9030,OU=Osprey,OU=District_Departments,DC=testlab,DC=local"
$SW_Group = "9030_SW_AllStaff"
}
9029 {
$Department = "9029 Facilities"
$ADDept = "OU=Staff,OU=Facilities Services 9029,OU=CFS,OU=District Departments,DC=testlab,DC=local"
$SW_Group = "9029_SW_AllStaff"
}
9033-PrintShop {
$Department = "9033 PrintShop"
$ADDept = "OU=Staff,OU=PrintShop-9033,OU=Osprey,OU=District Departments,DC=testlab,DC=local"
$SW_Group = "9030_SW_AllStaff"
}
#endregion cc
}
}
#Check to see if the user already exists in AD
if (Get-ADUser -F {SamAccountName -eq $Username})
{
#If user does exist, give a warning
Write-Warning "A user account with username $Username already exist in Active Directory."
}
else
{
#User does not exist then proceed to create the new user account
#Account will be created in the OU provided by the $OU variable read from the CSV file
$NewUserParams = @{
'SamAccountName' = $Username
'UserPrincipalName' = "$Username@testlab.local"
'Name' = "$LastName $FirstName"
'GivenName' = $Firstname
'Surname' = $Lastname
'Enabled' = $True
'DisplayName' = "$Lastname $Firstname"
'Description' = $Description
'Path' = $ADDept
'Company' = $company
'State' = $state
'Title' = $jobtitle
'Department' = $department
'AccountPassword' = (convertto-securestring $Password -AsPlainText -Force)
'Server' = "DC1.testlab.local"
}
New-AdUser @NewUserParams
}
You’re passing the $ADDept to the -Path parameter, where you’re putting bad values like “OU=Staff,OU=PrintShop-9033,OU=Osprey,OU=District Departments,DC=testlab,DC=local”
Users belong in a container like “CN=Staff,OU=PrintShop-9033,OU=Osprey,OU=District Departments,DC=testlab,DC=local” not in an OU…