I'm using a PowerShell script to create new users in AD from a CSV file. The script I have I've used before, and I'm sure it used to work without errors. However when I run it now, I get an error when trying to limit the samAccount name to 20 characters max. It actually works fine for names over 20 characters, it checks the length, and crops it to 20. The errors happens if the name is under 20 characters. The code I'm using is:
$sam = $_.GivenName.ToLower() + "." + $lastname.ToLower()
$length = 20
If ($sam -gt 20)
The error I get is:
Exception calling "Substring" with "2" argument(s): "Index and length must refer to a location within the string. Parameter name: length"
Not sure why it's erroring on characters under 20, I'm thinking it should only run if $sam is greater than 20, if not, it should skip on to the next function. How can I get rid of this error for names under 20 charactors?