Limiting a system variable's length within another variable.


i looking place system variable within variable using powershell, however, want limit length of variable. trying take logged in user's username, limit 8 characters, , place within variable. have:

$qwvar = $env:username

with line taking logged on user's username , setting variable $qwvar. however, if lets have username of mrodriguez, $qwvar variable hold first 8 characters making mrodrigu.

i new powershell not sure if possible entirely within powershell. have been working on awhile , thought come masters help.

thanks in advance.

mike

$env:username of type string. call string's substring method , pass start index , length of substring. in case 0 start index , 8 length of substring:

$env:username.substring(0, 8) 

…but run problems if , when length of value of $env:username less 8 characters. of course, handle error (or check value's length before retrieving first 8 characters) there safer way not need error handling.

since string concatenated array of characters ( char[] ), can use index notation retrieve first 8 characters so:

$env:username[0..7] 

…but returns char array , want string, no problem, use join operator, in unary form, tie characters in array:

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

so, final code be:

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


Windows Server  >  Windows PowerShell



Comments

Popular posts from this blog

Error: 0x80073701 when trying to add Print Services Role in Windows 2012 Standard

Disconnecting from a Windows Server 2012 R2 file sharing session on a Windows 7,8,10 machine

Windows 2016 RDS event 1306 Connection Broker Client failed to redirect the user... Error: NULL