Home > Mobile >  Using $env:USERNAME or other variables when executing a script
Using $env:USERNAME or other variables when executing a script

Time:06-15

So I've been writing a script in powershell, and I'd like to make a few alterations to allow people to use it with minimal effort on their part. Part of this includes adjusting the script so that instances of my username in paths are replaced with $env:USERNAME.

For example, C:\Users\{username}\Downloads\executable.exe

would become C:\Users\$env:USERNAME\Downloads\executable.exe

and the outcome would be the same.

I repeatedly get the error The term 'C:\Users\$env:USERNAME\Downloads\executable.exe' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again.

When I calling it as part of an assigned variable, I get The term C:\Users\{username}\Downloads\executable.exe is not ..., so the path is processed correctly in this case.

I've used variables in paths in bash before with 0 issue, so I'm unsure of where I'm going wrong.

I've tried assigning it to a variable and calling it, and assigning $env:USERNAME and including that variable in the path but neither worked.

I've tried using $env:HOMEPATH too.

I've tried assigning to a variable as a string (with double quotes), and using Invoke-command $command and Invoke-Expression $command but no dice.

How would I execute a script or an executable with a variable in the path name? Is this possible in powershell?


Mathias R. Jensen's answer fixed my issue, my code now works.

#Constructed path as advised
$TestPath = Join-Path $env:USERPROFILE \Downloads\executable.exe

Get-date | Out-File -FilePath $env:USERPROFILE\test\testfile.txt -Append
#Invoked executable
& $TestPath | Out-File -FilePath $env:USERPROFILE\test\testfile.txt -Append

CodePudding user response:

For constructing paths relative to the users profile folder, use $env:USERPROFILE, and split the operation into 2 separate steps:

  • Construct path to executable
  • Invoke with the & call operator:
# Construct path
$exePath = Join-Path $env:USERPROFILE 'Downloads\executable.exe'

# Invoke executable
& $exePath
  • Related