Powershell - Add string to variable with no line breaks

I am trying to do what I thought would be very simple and join a few strings together in a powershell script.  Here's what I have tried so far.

Example1: $userprofile = "C:\users\" + $user + "\"

Example2: $userprofile = [String]::Join("C:\users\", $user, "\")

Example3: $userprofile = [String]::Concat("C:\users\", $user, "\")

The result from each of these examples is the same, the first string ("C:\users\") and string variable ($user) are joined properly, but the last string ("\") is added after a line break so the output looks like this:

C:\users\daniel.smith

\

FYI: I know that I could just use the $userprofile system variable but the script will not be running under the logged on user's user context, however I still need to access the logged on user's profile, so I am getting the current user from WMI and building the userprofile path from that.

Any help would be appreciated.

June 24th, 2013 9:53pm

I think your code is correct, but you have a CRLF in the variable $User

$user = "UserA"
$userprofile = "C:\users\" + $user + "\"
$userprofile
C:\users\UserA\

$user = "UserB`n"
$userprofile = "C:\users\" + $user + "\"
$userprofile
C:\users\UserB
\

You see in the example with UserB i add a newline `n to the string UserB abd get our Output!

You can try this:
$userprofile = "C:\users\" + ($user -Replace('\n','')) + "\"


Free Windows Admin Tool Kit Click here and download it now
June 24th, 2013 10:30pm

That was the problem.  I didn't notice that at all until you mentioned it.  Thanks.
July 5th, 2013 8:43am

This topic is archived. No further replies will be accepted.

Other recent topics Other recent topics