Reputation: 120
I am building a PowerShell script to create an Active Directory account. The home directory for the user is based on the first letter of their username between a certain range:
I am struggling to implement something that outputs their needed directory. I managed to get it working with one directory set, however I cannot figure out how to change the output based on the first letter of their name.
$SAMAccountName = $Surname+$Initial
$SAMAccountLower = $SAMAccountName.ToLower()
$UserPrincipalName = $Surname+$Initial
$HD = "U"
$HDir = "\\RBHFILRED002\"
$AC = "Users_01$\"
$DH = "Users_02$\"
$IM = "Users_03$\"
$NS = "Users_04$\"
$TZ = "Users_05$\"
New-ADUser -path "REDACTED" -SamAccountName $Surname$Initial -Name $DisplayName -DisplayName $DisplayName -GivenName $GivenName -Surname $Surname -EmailAddress $Mail -UserPrincipalName $Surname$Initial@REDACTED -Title $title -HomeDrive $HD -HomeDirectory $HDir$Surname$Initial -Description $Description -ChangePasswordAtLogon $true -PasswordNeverExpires $false -AccountPassword $defpassword -Enabled $true -PassThru
I think I basically need to refine by the first letter of their surname, and sort it into one of the groups, to then output the right Users folder for the home directory.
Upvotes: 1
Views: 1089
Reputation: 23355
You could do this:
$AC = 97..99 | ForEach-Object { [char]$_ }
$DH = 100..104 | ForEach-Object { [char]$_ }
$IM = 105..109 | ForEach-Object { [char]$_ }
$NS = 110..115 | ForEach-Object { [char]$_ }
$TZ = 116..122 | ForEach-Object { [char]$_ }
$HomePath = Switch ($Surname[0]) {
{$_ -in $AC} { 'Users_01$\' }
{$_ -in $DH} { 'Users_02$\' }
{$_ -in $IM} { 'Users_03$\' }
{$_ -in $NS} { 'Users_04$\' }
{$_ -in $TZ} { 'Users_05$\' }
}
This uses the ASCII character codes for (lowercase) a..z to create the different arrays of letters, then uses a Switch
block to compare the first letter of $Surname
(by using the array operator [0]
) to each array to specify a home directory path (which is then assigned to $HomePath
).
Alternatively you could also do this:
$HomePath = Switch ([byte][char]$Surname[0]) {
{$_ -in 97..99} { 'Users_01$\' }
{$_ -in 100..104} { 'Users_02$\' }
{$_ -in 105..109} { 'Users_03$\' }
{$_ -in 110..115} { 'Users_04$\' }
{$_ -in 116..122} { 'Users_05$\' }
}
This converts the first letter of the surname in to its ASCII code number and then uses the ascii code ranges to determine which path is correct. This solution is shorter but perhaps less transparent/clear to anyone else who might have to modify/maintain your code in the future.
Also (FYI) if you are using PowerShell Core, you can now create an array of characters with the ..
operator directly. E.g you can do: 'a'..'z'
in PowerShell Core.
Upvotes: 1