Search code examples
windowspowershellactive-directory

Set User logon name (pre-windows 2000) using Powershell Script


How do set this variable using powershell?

enter image description here

$firstName = Read-Host -Prompt "Enter first name: "
$lastName = Read-Host -Prompt "Enter last name: "
$username = Read-Host -Prompt "Enter username: "
...


New-ADUser `
-Name $displayName `
-GivenName $firstName `
-Surname $lastName `
-DisplayName $displayName `
-UserPrincipalName $pName `
-AccountPassword(ConvertTo-SecureString $password -AsPlainText -Force) `
-PasswordNeverExpires $True `
-Description $description `
-EmailAddress $email `
-Path $path `
-Enabled $true
 
 Get-ADUser -Identity $displayName

I am trying to write a script for user creation. I would like to set the user logon name (pre-windows 2000) while I'm running the script and entering thee user information.


Solution

  • You just need as include the -sAMAccountName attribute. So

    New-ADUser `
    -Name $displayName `
    -GivenName $firstName `
    -Surname $lastName `
    -DisplayName $displayName `
    -sAMAccountName $samaccountname `
    -UserPrincipalName $pName `
    -AccountPassword(ConvertTo-SecureString $password -AsPlainText -Force) `
    -PasswordNeverExpires $True `
    -Description $description `
    -EmailAddress $email `
    -Path $path `
    -Enabled $true
     
     Get-ADUser -Identity $displayName
    

    Note, keep in mind that the SamAccountName aka "user logon name (pre-windows 2000)" has a maximum character length of 20 characters. So when validating your inputs you probably want to check that the entered value isn't too long, for instance

    if ($samaccountname.length -gt 20)
    {
       Write-Output "Error, entered username is longer than 20 characters"
       break
    }