2

I'm trying to run the following script that I thought was quite simple. What am I doing wring here...

[Environment]::UserName = $username

Write-Host "The user is $username"
$from = "c:\Users\" + $username + "\favourites\*.*" 
$to = "c:\test"

Write-Host "This is from dir: $from"
Write-Host "This is to dir: $to"

Copy-Item $from $to

The script does not seem to like the + $username + ...

1 Answer 1

8

I think you got your first line the wrong way around. Currently you're assigning an empty variable (value of it should be $null) to $Env:UserName, thus overwriting the username, not reading it.

I think it should be

$username = [Environment]::Username

or, as noted above, you can access environment variables via the special Env: drive:

$username = $Env:Username

And unrelated to your problem, just a matter of nicer code:

  1. You can put the username directly into the string (which you seem to know, as demonstrated a line above – where you don't need a string in this case, though):

    $from = "C:\Users\$username\favourites\*"
    
  2. You don't need to fetch the user name at all, you can use

    $Env:UserProfile
    

    or

    [Environment]::GetFolderPath([Environment+SpecialFolder]::UserProfile)
    

    or even

    [Environment]::GetFolderPath([Environment+SpecialFolder]::Favorites)
    

    which might ultimately be what you're after, here.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.