PowerShell – Exception calling “Substring” with argument(s)

My colleague Rob (Check out his Blog here) and I have been hard at work creating a runbook in Orchestrator 2012 to automate account creation for our organisation. While looking at the process and running some tests, we found a flaw in the substring PowerShell command thanks to John Doe!

The Error:

$sn = "Doe"$sn.Substring( 0, 5) #First 5 letters of the last name (SN)


Exception calling “Substring” with “2” argument(s): “Index and length must refer to a location within the string. Parameter name: length”

Its a great one right!? The reason for this is the substring will only count the number specified and doesn’t compensate if the string is less then 5. So how do we fix this? Well we trap the length using the below.

If ($checklength -lt 5 )$numberx = $checklength}Else{$numberx = 5}
$sn5 = $sn.Substring( 0, $numberx) #First 5 letters of the last name (SN)

This will check the length of $sn then if its less than 5, it will set the number variable to the length else it will set it to 5.

Leave a Reply

Your email address will not be published. Required fields are marked *