BReadHeaD
BReadHeaD

Reputation: 11

ADuser not adding samAccountName after changing Variable

Thanks in advance !

I have made a script and in this script, I add users from excel to AD and it works for 99% but I need to make 1 change to it but when I do that it gives me errors.

Import-Csv -Path C:\Users\admin.kln\Documents\Project\BOSAN_USERS.csv |foreach{

#All strings of variables you need out of excel
$Firstname = $_.Firstname
$Lastname = $_."Last Name"
$Displayname = $_."Display Name"
$Extraname = $_."Display Name"
$Logonname = $_."Logon Name"
$Accountpassword = $_.AccountPassword
$Description = $_.Description
$Jobtitle = $_."Job Title"
$Department = $_.Department
$Company = $_.Company
$Telephonenumber = $_.TelephoneNumber
$Mobilenumber = $_."Mobile number"
$Street = $_.Street
$PObox = $_."P.O. Box"
$City = $_.City
$State = $_."State / Province"
$Zip = $_.Zip
$Country = $_.Country
$Manager = $_.Manager
$ProxyEmail = $_."Proxy Address + Email(SMTP)"
$ProxyAdress = $_."Proxy Addresss(smpt)"
$ProxySip = $_."Proxy address (SIP)"
$Final = (($_.Firstname.ToLower().Substring(0,1)) + '.' + ($_."Last name".ToLower()))

#int
$i = 1
$u = 1
$o = 1
#Check if its over 18 chars if it is it will be shortened
if ($Displayname.Length -gt 18) { $Displayname = $Displayname.Substring(0,18) }
if ($Extraname.Length -gt 18) { $Extraname = $Extraname.Substring(0,18) }

try
    {
        while (Get-ADUser -F {SamAccountName -eq $Extraname})
        {
            Write-Warning "Er bestaat al een account met de naam $Extraname"
            $Extraname = $Displayname + [string]$i
            $i++
            
            $Logonname = $Logonname + [string]$o
            $o++

            $Final = (($_.Firstname.ToLower().Substring(0,1)) + '.' + ($_."Last Name".ToLower()))
            $Final = $Final + [string]$u
            $u++
        }
    }
catch{}
finally
        {

            $Logonname = $Logonname -replace ' ',''
            $Final = $Final -replace ' ',''
            echo $Final
            New-ADUser -Path "ou=Users,ou=NLHKH,dc=CONTOSO,dc=com" `
            -SamAccountName $Extraname `
            -GivenName $Firstname `
            -Name $Extraname `
            -Surname $Lastname `
            -DisplayName $Extraname `
            -UserPrincipalName $Final `
            -accountpassword(ConvertTo-SecureString "Password1" -AsPlainText -force) `
            -ChangePasswordAtLogon $true `
            -Description $Description `
            -Title $Jobtitle `
            -Department $Department `
            -Company $Company `
            -MobilePhone $Mobilenumber `
            -StreetAddress $Street `
            -City $City `
            -State $State `
            -PostalCode $Zip `
            -POBOX $PObox 
            

        }
}

As you can see it should work like this but I need to change -SamAccountName to $final or at least to the same Variable as $Final. But that won't do.

this is how it counts

Upvotes: 0

Views: 694

Answers (1)

Theo
Theo

Reputation: 61068

Personally, I would change quite a lot of your script.

First of all, you need two loops to figure out if

  1. you get a valid unique SamAccountName
  2. you get a valid unique UserPrincipalName

The ProxyAddresses need extra care aswell. You need to create an array of the 3 Proxy* fields in the CSV and add that with parameter OtherAttributes. Mind that his will not accept a 'normal' array and that it needs to be cast with [string[]] to form a strongly typed string array.

Finally, use Splatting for the New-ADUser cmdlet to get rid of those nasty backticks.

Something like this:

Import-Csv -Path 'C:\Users\admin.kln\Documents\Project\BOSAN_USERS.csv' | ForEach-Object {
    # unused fields in the CSV:
    # $Logonname = $_."Logon Name"
    # $Country = $_.Country
    # $Manager = $_.Manager

    # construct a SamAccountName from the DisplayName in the CSV
    # replace all invalid characters and cut off anything over 20 characters
    $SamAccountName = $_."Display Name" -replace '[\x00-\x20"[\]:;|=+*?<>/,@\s]'
    if ($SamAccountName.Length -gt 20) { $SamAccountName = $SamAccountName.Substring(0, 20) }
    $temp = $SamAccountName
    # enter an endless loop to test if that user with that SamAccountName already exists
    $i = 1
    while ($true) {
        $user = Get-ADUser -Filter "SamAccountName -eq '$SamAccountName'" -ErrorAction SilentlyContinue
        # if a user with that SamAccountName does not yet exist, we can break out of the loop
        if (!$user) { break }

        # create a new SamAccountName to test
        while (($temp + $i).Length -gt 20) { 
            $temp = $temp.Substring(0, $temp.Length - 1) 
        }
        $SamAccountName = '{0}{1}' -f $temp, $i
        $i++
    }

    # since your UPN uses a different format than '[email protected]', 
    # start another loop to make sure that too is unique
    # CHANGE @CONTOSO.com TO THE REAL DOMAIN NAME
    $UserPrincipalName = '{0}.{1}@CONTOSO.com' -f $_.Firstname.Substring(0,1).ToLower(), $_."Last name".ToLower()
    $i = 1
    while ($true) {
        $user = Get-ADUser -Filter "UserPrincipalName -eq '$UserPrincipalName'" -ErrorAction SilentlyContinue
        # if a user with that UserPrincipalName does not yet exist, we can break out of the loop
        if (!$user) { break }

        # create a new UserPrincipalName by adding a sequence number to test
        $UserPrincipalName = '{0}.{1}{2}@CONTOSO.com' -f $_.Firstname.Substring(0,1).ToLower(), $_."Last name".ToLower(), $i
        $i++
    }

    # next, create an array of the Proxy Addresses. Watch the spelling in the CSV headers!
    $ProxyAddresses = ('SMTP:{0}' -f ($_."Proxy Address + Email(SMTP)" -replace '^SMTP:')),
                      ('smtp:{0}' -f ($_."Proxy Address(smpt)" -replace '^smtp:')),
                      ('SIP:{0}'  -f ($_."Proxy address (SIP)" -replace '^SIP:'))

    # now that we have unique names and a ProxyAddresses array, we can create the user
    $NewUserParms = @{
        'SamAccountName'        = $SamAccountName
        'Name'                  = ('{0} {1}' -f $_.FirstName, $_."Last Name").Trim()
        'DisplayName'           = $_."Display Name"
        'UserPrincipalName'     = $UserPrincipalName
        'GivenName'             = $_.FirstName
        'Surname'               = $_."Last Name"
        'Description'           = $_.Description
        'Title'                 = $_."Job Title"
        'Department'            = $_.Department
        'Company'               = $_.Company
        'AccountPassword'       = ConvertTo-SecureString $_.AccountPassword -AsPlainText -Force
        'ChangePasswordAtLogon' = $true
        'Enabled'               = $true
        'OfficePhone'           = $_.TelephoneNumber
        'MobilePhone'           = $_."Mobile number"
        'StreetAddress'         = $_.Street
        'City'                  = $_.City
        'State'                 = $_."State / Province"
        'PostalCode'            = $_.Zip
        'POBox'                 = $_."P.O. Box"
        'EmailAddress'          = $_."Proxy Address + Email(SMTP)" -replace '^SMTP:'
        'Path'                  = "OU=Users,OU=NLHKH,DC=CONTOSO,DC=com"
        # ProxyAddresses needs cast to [string[]]
        'OtherAttributes'       = @{'proxyAddresses' = [string[]]$ProxyAddresses}  

        # add other properties to set from the CSV here if needed.
        # make sure you get the parameter data types correct and always check here:
        # https://learn.microsoft.com/en-us/powershell/module/addsadministration/new-aduser?view=win10-ps#parameters
        # switch parameters for the cmdlet can also be entered with a value $false or $true
    }

    try {
        # '-ErrorAction Stop' ensures that also non-terminating errors get handled in the catch block
        New-ADUser @NewUserParms -ErrorAction Stop
    }
    catch {
        # something bad happened. Change 'Write-Warning' into 'throw' if you want your script to exit here
        # inside a catch block, the '$_' automatic variable represents the actual exception object.
        Write-Warning "Could not create account $username. $($_.Exception.Message)"
    }
}

Upvotes: 1

Related Questions