Solved

Limit String to Specific Length

Posted on 2014-10-13
2
1,163 Views
Last Modified: 2014-10-13
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) 
        {
        $sam=$sam.Substring(0,$length) 
        }

Open in new window

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?
0
Comment
Question by:bjblackmore
2 Comments
 
LVL 40

Accepted Solution

by:
Subsun earned 500 total points
ID: 40378357
Use the following condition to check the length..  If ($sam -gt 20) will not check the length of the string..
If ($sam.Length -gt 20)

Open in new window

0
 
LVL 29

Expert Comment

by:becraig
ID: 40378390
$sam = $_.GivenName.ToLower() + "." + $lastname.ToLower()
$length = 20
If ($sam.length -ge 20) 
{
$sam=$sam.Substring(0,$length) 
}

Open in new window


Edit:
Disregard I see Subsun already responded
0

Featured Post

DevOps Toolchain Recommendations

Read this Gartner Research Note and discover how your IT organization can automate and optimize DevOps processes using a toolchain architecture.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

In this previous article (https://oddytee.wordpress.com/2016/05/05/provision-new-office-365-user-and-mailbox-from-exchange-hybrid-via-powershell/), we made basic license assignments to users in O365. When I say basic, the method is the simplest way …
A procedure for exporting installed hotfix details of remote computers using powershell
Learn the basics of if, else, and elif statements in Python 2.7. Use "if" statements to test a specified condition.: The structure of an if statement is as follows: (CODE) Use "else" statements to allow the execution of an alternative, if the …
This tutorial will teach you the core code needed to finalize the addition of a watermark to your image. The viewer will use a small PHP class to learn and create a watermark.

777 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question