Karthik
Karthik

Reputation: 349

AD samAccountname scripting error

I'm trying to input a csv file, which contains Givename & Lastname information of the users. When I run the command listed below samAccountName does not give me the expected output.

Please see below and let me know what should be corrected.

Input:

GivenName,LastName,Password,TargetOU,Description,Manager
Jeffrey,Terry,Pass12,"OU=Users,DC=mmc,DC=local",mmc user,knadella
A,King,Pass13,"OU=Users,DC=mmc,DC=local",mmc user,knadella
Chris ,Charles,Pass14,"OU=Users,DC=mmc,DC=local",mmc user,knadella

Command:

$samAccountName = ($csvcontent.GivenName.Substring(0,1))+( $csvcontent.LastName)

Current Output:

J A C Terry King Charles

Desired Output:

ATerry, AKing and CCharles 

Please assist.Thank you!!

Upvotes: 0

Views: 270

Answers (3)

Avshalom
Avshalom

Reputation: 8889

You need to itterate each item and not the whole array at once:

$samAccountName = $csvcontent | % {
($_.GivenName.Substring(0,1))+($_.LastName)
}

Upvotes: 0

Zach Olinske
Zach Olinske

Reputation: 557

Going to give you what I use about 30 times a day. The way you are looking to create it will break some login options.

# <FirstLetterGivingName><LastName> for example
# WGates (William Gates)
 $sam = $_.GivenName.substring(0,1)+$_.Lastname

That is a good thing, but as the company grows, you will start to run into an issue where the usernames are the same. This is not a perfect solution, but having GivenName (0,3) will give you the first three letters. This will usually fix this issue. It is really rare if you hit someone with the same first three letters and lastname, but it could happen.

$sam = $_.GivenName.substring(0,3)+$_.Lastname

I have also seen companies do this, but advise not to do this, because it would be hard for the user to remember the login.

$sam = $_.GivenName.substring(0,1)+$_.Lastname.substring(0,7)

This script has been used thousands of times, but has been edited a little for this post.

#Test to make sure your output looks correct
#You can do this by running the following:
#Import-csv ".\import_create_ad_users.csv" | Out-GridView

# ERROR REPORTING ALL
Set-StrictMode -Version latest
Import-Module ActiveDirectory

#----------------------------------------------------------
#STATIC VARIABLES
#----------------------------------------------------------

$path = Split-Path -parent $MyInvocation.MyCommand.Definition
$newpath = $path + ".\import_create_ad_users.csv"
$log = $path + ".\create_ad_users.log"
$date = Get-Date
$i = 1
#$addn = (Get-ADDomain).DistinguishedName
#$dnsroot = (Get-ADDomain).DNSRoot
$DNdom = Get-ChildItem -Path Ad:\ | where {$_.Name -eq "Configuration"}            
$addn = ($DNdom.DistinguishedName -split "," ,2)[1] 
$wmiDomain = Get-WmiObject Win32_NTDomain -Filter "DnsForestName = '$( (Get-WmiObject Win32_ComputerSystem).Domain)'"
$dnsroot = $wmiDomain.DomainName  + ".local"

#----------------------------------------------------------
#START FUNCTIONS
#----------------------------------------------------------
Function Start-Commands
{
  Create-Users
}

Function Create-Users
{
  "Processing started (on " + $date + "): " | Out-File $log -append
  "--------------------------------------------" | Out-File $log -append
  Import-CSV $newpath | ForEach-Object {
      If (($_.GivenName -eq "") -Or ($_.LastName -eq ""))
      {
        Write-Host "[ERROR]`t Please provide valid GivenName and LastName. Processing skipped for line $($i)`r`n"
        "[ERROR]`t Please provide valid GivenName and LastName. Processing skipped for line $($i)`r`n" | Out-File $log -append
      }
      Else
       {

        # Replace dots / points (.) in names, because AD will error when a 
        # name ends with a dot (and it looks cleaner as well)
        $replace = $_.Lastname.Replace(".","")
        If($replace.length -lt 4)
            {
            $lastname = $replace
            }
        Else
            {
            $lastname = $replace.substring(0,4)
            }
        # Create sAMAccountName according to this 'naming convention':
        # <FirstLetterInitialGivingName><LastName> for example
        # WGates (William Gates)
        $sam = $_.GivenName.substring(0,1)+$_.Lastname
        Try   { $exists = Get-ADUser -LDAPFilter "(sAMAccountName=$sam)" }
        Catch { }
        If(!$exists)
            {
          # Set all variables according to the table names in the Excel 
          # sheet /import CSV. The names can differ in every project, but 
          # if the names change, make sure to change it below as well.
          $setpass = ConvertTo-SecureString -AsPlainText $_.Password -force

          Try
          {
            Write-Host "[INFORMATION]`t User is now being built : $($sam)"
            "[INFORMATION]`t User is now being built : $($sam)" | Out-File $log -append
            New-ADUser $sam -path $_.TargetOU -GivenName $_.GivenName -Initials $_.Initials `
            -Surname $_.LastName -UserPrincipalName ($sam + "@" + $dnsroot) -DisplayName ($_.GivenName + " " + $_.LastName) `
            -Description $_.Description -Manager $_.Manager -AccountPassword $setpass -Enabled $TRUE -ChangePasswordAtLogon $TRUE
            Write-Host "[INFORMATION]`t Created a new user named : $($sam)"
            "[INFORMATION]`t Created new user named: $($sam)" | Out-File $log -append

             $dn = (Get-ADUser $sam).DistinguishedName

            # Rename the object to a good looking name
            $newdn = (Get-ADUser $sam).DistinguishedName
            Rename-ADObject -Identity $newdn -NewName ($_.GivenName + " " + $_.LastName)
            Write-Host "[INFORMATION]`t Renamed the user $($sam) to $($_.GivenName) $($_.LastName)`r`n"
            "[INFORMATION]`t Renamed the user $($sam) to $($_.GivenName) $($_.LastName)`r`n" | Out-File $log -append

          }
          Catch
          {
            Write-Host "[ERROR]`t Oops, something went wrong: $($_.Exception.Message)`r`n"
          }
        }
        Else
        {
          Write-Host "[SKIP]`t User $($sam) ($($_.GivenName) $($_.LastName)) already exists or returned an error!`r`n"
          "[SKIP]`t User $($sam) ($($_.GivenName) $($_.LastName)) already exists or returned an error!" | Out-File $log -append
        }
      }
    Else
    {
      Write-Host "[SKIP]`t User ($($_.GivenName) $($_.LastName)) will be skipped for processing!`r`n"
      "[SKIP]`t User ($($_.GivenName) $($_.LastName)) will be skipped for processing!" | Out-File $log -append
    }
    $i++
  }
  "Processing ended (on " + $date + "): " | Out-File $log -append
  "--------------------------------------------" + "`r`n" | Out-File $log -append
}


Write-Host "***************************SCRIPT HAS STARTED***************************"
Write-Host "***************************SCRIPT HAS STARTED***************************"
Write-Host "***************************SCRIPT HAS STARTED***************************`r`n"
Start-Commands
Write-Host "***************************SCRIPT HAS FINISHED***************************"
Write-Host "***************************SCRIPT HAS FINISHED***************************"
Write-Host "***************************SCRIPT HAS FINISHED***************************"

Your CSV would have the following headers:

GivenName LastName LoginName Description Password Manager TargetOU

Upvotes: 0

G42
G42

Reputation: 10019

You are aggregating all of the details in one go, combining the results of the GivenNamecolumn (J A C) with the results of the LastName column (Terry King Charles)`

This loops over each user:

foreach($user in $csvcontent){
    [array]$samAccountName += $user.GivenName[0] + $user.LastName
}

Output:

JTerry AKing CCharles

Upvotes: 1

Related Questions