0

I am writing a script to copy a file to the current logged in user. The code below I think will work but I need to replace "username" with the variable $CurrentLoggedinUser.

C:\Users\username\AppData\LocalLow\Sun\Java\Deployment\security to something like this C:\Users\$CurrentLoggedinUser\AppData\LocalLow\Sun\Java\Deployment\security

Any idea how I can do this? TIA

$CurrentLoggedinUser = $env:UserName
Copy-Item -Path **/*.CERTS -Destination C:\Users\username\AppData\LocalLow\Sun\Java\Deployment\security 
user1342164
  • 1,434
  • 13
  • 44
  • 83
  • 2
    `$env:UserProfile + '\AppData\LocalLow\Sun\Java\Deployment\security'` – Aluan Haddad Jan 23 '18 at 20:03
  • Try `Get-ChildItem($MyInvocation.MyCommand.Path) -Directory` see [this answer](https://stackoverflow.com/questions/8343767/how-to-get-the-current-directory-of-the-cmdlet-being-executed) – Aluan Haddad Jan 23 '18 at 20:24
  • 1
    @AluanHaddad: Perhaps you meant `Split-Path -Parent $MyInvocation.MyCommand.Path` to get the script's folder? Or, in PSv3+, `$PSScriptRoot`? – mklement0 Jan 25 '18 at 02:50
  • 1
    Probably, I'm not a very advanced Powershell user. The command I suggested worked when I tested it but maybe I misunderstood something. – Aluan Haddad Jan 25 '18 at 03:59

1 Answers1

1

Your question is more generally about how to incorporate variable references into command arguments / strings:

In the simplest case, simply replace literal parts with $var references, where var is the name of the variable of interest:

C:\Users\$CurrentLoggedinUser\AppData\LocalLow\Sun\Java\Deployment\security

For added robustness, enclose the name in {...} so that subsequent chars. cannot be mistaken for part of the name:

C:\Users\${CurrentLoggedinUser}\AppData\LocalLow\Sun\Java\Deployment\security

Of course, you can directly reference environment variables too:

C:\Users\${env:USERNAME}\AppData\LocalLow\Sun\Java\Deployment\security

Or, given that the current user's profile dir. is accessible as $env:USERPROFILE:

$env:USERPROFILE\AppData\LocalLow\Sun\Java\Deployment\security

All of the above work as an argument to a command, that is to say, in when parsing in argument mode rather than expression mode - see Get-Help about_Parsing.

In expression mode, you need to quote strings such as the ones above; in order to incorporate variable references (or even the output from entire commands via $(...)), you must double-quote them (which makes them so-called expandable strings - see Get-Help about_Quoting_Rules).

Note only do quoted strings work in argument mode too, their use may be necessary for strings that contain characters that have special meaning in argument mode, such as &, @, or >.

Thus, the equivalent of the above is simply:

"$env:USERPROFILE\AppData\LocalLow\Sun\Java\Deployment\security"
mklement0
  • 382,024
  • 64
  • 607
  • 775