user1342164
user1342164

Reputation: 1454

How can I place variable in a folder path?

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 

Upvotes: 0

Views: 3272

Answers (1)

mklement0
mklement0

Reputation: 440297

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"

Upvotes: 1

Related Questions