Solved

Limit String to Specific Length

Posted on 2014-10-13
2
960 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 28

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

How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

Join & Write a Comment

Active Directory replication delay is the cause to many problems.  Here is a super easy script to force Active Directory replication to all sites with by using an elevated PowerShell command prompt, and a tool to verify your changes.
Set OWA language and time zone in Exchange for individuals, all users or per database.
The viewer will learn how to look for a specific file type in a local or remote server directory using PHP.
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.

707 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

Need Help in Real-Time?

Connect with top rated Experts

13 Experts available now in Live!

Get 1:1 Help Now