Share via


Limiting a system variable's length within another variable.

Question

Saturday, April 14, 2012 7:34 PM

I am looking to place a system variable within another variable using powershell, however, I want to limit the length of the variable. I am trying to take the logged in user's username, limit it to only 8 characters, and place it within another variable. I currently have:

$qwvar = $env:username

With this line I am simply taking the logged on user's username and setting it to the variable $qwvar. However, if lets say I have a username of MRodriguez, I would like the $qwvar variable to only hold the first 8 characters making it MRodrigu.

I am very new to powershell so I am not even sure if this is possible entirely within powershell. I have been working on this for awhile now and thought I would come to the masters for some help.

Thanks in advance.

Mike

All replies (2)

Saturday, April 14, 2012 9:07 PM ✅Answered

$env:USERNAME is of type String. You could call String's Substring method and pass the Start index and the Length of the substring. In your case 0 would be the Start index and 8 the length of the substring:

$env:username.Substring(0, 8)

…but you could run into problems if and when the length of the value of $env:username is less than 8 characters. Of course, you could handle the error (or check the value's length before retrieving its first eight characters) but there is a safer way that does not need error handling.

Since a String is really a concatenated array of characters ( Char[] ), you can use index notation to retrieve its first eight characters like so:

$env:username[0..7]

…but that returns a Char array and you want a String, no problem, just use the Join operator, in its unary form, to tie the characters in the array:

-join $env:username[0..7]

So, the final code would be:

$qwvar = -join $env:username[0..7]

Monday, April 16, 2012 8:58 PM

This script worked perfectly. Thank you for your help.