'New-ADUser and SAMAccountName limit

I've put together a script that creates accounts in AD and assigns a bunch of info including group membership based on input from a CSV. I use the .Substring method to create a temporary password using parts of the new hire's name. But when I try to set the SamAccountName using the .Substring method to grab the first 20 characters of the username with the same syntax as when I set the password, I'm treated to errors.

Within the same New-ADUser command, why does the below set the password as the first character of their FirstName followed by the first character of their LastName just like I would expect

-AccountPassword (convertto-securestring($Firstname.Substring(0,1)+$Lastname.Substring(0,1)) -AsPlainText -Force)

While the below does not set the SamAccountName as the first 20 characters of the Username? I get errors no matter how I've tried to do it.

-SamAccountName ($Username.Substring(0,20))

Error below:

Exception calling "Substring" with "2" argument(s): "Index and length must refer to a location within the string.Parameter name: length"At C:\Create_AD_Users.ps1:28 char:7+
New-ADUser `+ ~~~~~~~~~~~~ + CategoryInfo : NotSpecified: (:) [], MethodInvocationException + FullyQualifiedErrorId : ArgumentOutOfRangeException



Solution 1:[1]

here's a demo of what i meant by using regex to grab UP TO the limit instead of trying to grab ALL the limit.

what the code does ...

  • creates an array of strings to work with
    just use your own when you get ready to do this for real.
  • sets the max number of chars to capture
  • iterates thru the collection of strings
  • shows the original string
  • uses regex to capture up to $MaxChars from the string
    if you want details on the exact working of the regex pattern, please go to ...
    regex101: build, test, and debug regex
    == https://regex101.com/
    the box in the upper right will explain the meaning of any regex pattern you put into the box in the upper center.
  • displays that result
  • draws a divider that is 20 chars long

the code ...

#region >>> make some strings to work on
# the below strings are 29, 30, 20, and 10 chars long
$InStuff = @'
Abcdefghi_Bcdefghij_Cdefghijk
123456789_123456789_123456789_
Qwertyuio_Asdfghjkl_
123456789_
'@ -split [System.Environment]::NewLine
#endregion >>> make some strings to work on

$MaxChars = 17

foreach ($IS_Item in $InStuff)
    {
    $IS_Item
    $IS_Item -replace "^(.{0,$MaxChars}).*$", '$1'
    # yes, you can multiply strings [*grin*] 
    '=' * 20
    }

output ...

Abcdefghi_Bcdefghij_Cdefghijk
Abcdefghi_Bcdefgh
====================
123456789_123456789_123456789_
123456789_1234567
====================
Qwertyuio_Asdfghjkl_
Qwertyuio_Asdfghj
====================
123456789_
123456789_
====================

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Lee_Dailey