Two problems. If you want variable/expression substitution to take place in a string, you need to use quotation-marks, not apostrophes, to enclose the string. In this case, you also need to add some parenthesis to denote an expression within the string.

"\\SERVER\PATH\TO FILES\$([Environment]::UserName)\Normal\"
Answer from OldFart on Stack Overflow
🌐
Spiceworks
community.spiceworks.com › programming & development
Username variable in Powershell script - Programming & Development - Spiceworks Community
March 19, 2019 - Hey all, it’s your friendly PowerShell newbie again. I’ll be picking up some PowerShell books here in the next few weeks, but until then, I am tinkering away with the Internet at my side. I have another learning scenario that I was wondering if I can incorporate a username variable into, ...
🌐
Reddit
reddit.com › r/powershell › using $env:username or other variables in a script.
r/PowerShell on Reddit: Using $env:USERNAME or other variables in a script.
June 14, 2022 -

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'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 assigning to a variable as a string, and using Invoke-command $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?

EDIT I asked in more detail on stackexchange, link below https://stackoverflow.com/questions/72615928/using-envusername-or-other-variables-when-executing-a-script Solved by assigning a variable that joined $env:USERPROFILE and the rest of the path.

🌐
ShellGeek
shellgeek.com › home › powershell › how to use powershell variable in path
How to Use PowerShell Variable in Path - ShellGeek
April 14, 2024 - # Access the username path $userName = $env:USERNAME # Access the user profile path $userProfile = $env:USERPROFILE · In the above PowerShell script, the $env:USERPROFILE variable gets the path variable value and stores it in another variable.
🌐
TechTarget
techtarget.com › searchitoperations › answer › Manage-the-Windows-PATH-environment-variable-with-PowerShell
Manage the Windows PATH environment variable with PowerShell | TechTarget
For instance, if you place the Set-PathVariable function at the top of your profile.ps1, you can now add a path using the following: ... Now every time you launch PowerShell, it will add that path to your PATH variable.
🌐
Reddit
reddit.com › r/powershell › i'm new to this. is there a variable i can use to call the current user's username in a script path?
r/PowerShell on Reddit: I'm new to this. Is there a variable I can use to call the current user's username in a script path?
February 9, 2022 -

I'm running a script from a specific location and I want the script to call on itself at the end. What I mean by this is the very last line of this script is

c:\Users\Username\Documents\MFACheck.ps1

However, I want this to work for anyone who uses the script. When I have my username in the the place of the "Username" in the path above, the script acts as I want it to. Is there a variable that can call on the current logged in user's username to place in that spot? Note that PowerShell needs to be run as an admin, but PowerShell will be used from a non-admin account. I don't know if that will change how the variable I'm looking for can be called. Thanks in advance!

Edit: I found something that works! Using some information from this link: https://adamtheautomator.com/how-to-get-the-current-user-logged-on-with-powershell-all-the-ways/ As well as with help from u/monkeybutt227

I am now using Invoke-Expression -Command "c:\Users$(((Get-WMIObject -ClassName Win32_ComputerSystem).Username).Split('')[1])\Documents\MFACheck.ps1"

and it's working!

Top answer
1 of 2
11
$env:username
2 of 2
2
This post needs a little more information up front in order to get the right help. I see you've got a solution at this point, but I want to offer you some tips for both requesting assistance and doing this operation in the future: With a request for assistance that involves technical information, be sure to give enough context. In the case here, until your post update there was not a clear indication of specifically what commands you were using when encountering the error, aside from the specific string. You did include the error in a couple replies, that was good, but again the full context would really help us understand your exact scenario. As a follow-on to the above, your scenario is still a little confusing - in what way do you mean Powershell will be run as admin, from a non-admin account? What method does this mean you are using, and what is your implementation of this method? This matters because in the context of your request the value of the username could be available in different places with different values. The full context probably would have led to a faster resolution. When you write scripts, try to remember that you are not just instructing a computer to do things - you're also communicating to whomever might read this code in the future what your intent was. Powershell makes it very easy and in a lot of cases cool-looking to use shorthand syntax or complex one-liners to combine multiple commands into one expression. But this runs counter to the desire to clearly communicate what you mean your code to do. Try to practice clarity of code above all else - good code is often easy to understand code. I give an example from your post update in a reply to this comment. Powershell variable expansion is a whole beast unto itself. There are many ways to store and retrieve information in variables, and even more ways in which they can go wrong or do unexpected things. Learn to practice assembling your data in the safest and most predictable manner possible by forcing variables to expand in a controlled way and assembling strings or other arguments with expressions that evaluate in ways that you predict and control. The example in my reply to this comment is also related to this. Whenever you are presented with an expression that you feel needs to include array indexing syntax, such as '[1]' in your solution, take a moment to re-evaluate if the data you are operating on is predictable. There are two primary ways this technique is basically guaranteed to fail: either you have made a false assumption about the static-ness of the array you are indexing into and the array will at some point contain different data at the index you point at, or you will encounter a null condition where the index you point at does not even exist. Beyond the outright failure, there is an even worse problem: if your assumption about the index location is incorrect, you will eventually find a case where the index is location is valid but the data within it is not. Unless you are very careful with your validation routines, this will inevitably lead to a scenario where you took the wrong action on or with the wrong data - this will result in either data loss, perhaps catastrophically, or an unhandled exception. Imagine your script is working with data in a database, and your array index assumption is bad - could you even *find* the data that your script erroneously modified? To avoid these scenarios, carefully evaluate the constructs that contain data you operate on, and do everything possible to avoid using indexing. If you must rely on it, note that if you ever use anything other than [0] or [-1] (first and last value, respectively) you are almost definitely doing something wrong. Building on the above point, make sure you're getting your data from the right place. Sometimes you are forced to parse for your data in creative ways, but when you do this take a moment and see if you can find another source for the data that might be more direct or even authoritative. Based on your comments on this post, you were not actually looking for the username of the user running the code, but instead the username of another user logged in (presumably interactively). This information is available in a number of ways, but if we make three assumptions this becomes trivial: a) the user name you are looking for is not the name of the user executing the code, b) the user name you are looking for is the only user logged in interactively, c) the script is running with admin rights. With that in mind, we can reduce this to a method that can help us get the answer more directly, and also provide us with a validation opportunity that can stop us from potentially making an error. See reply to this comment.
🌐
Microsoft Learn
social.technet.microsoft.com › Forums › office › en-US › 5cb1bf92-0f1a-4169-a72f-d2a9e40ac432 › username-variable-in-powershell
%username% variable in Powershell | Microsoft Learn
April 1, 2022 - get-childitem -path \ums4455\env:USERNAME -recurse -filter cache ... So, for a better understanding ... you run a scheduled task with a dedicated account from a member server or whatever to cleanup a share ? The task is running directly on windows server hosting files or remotely on the share ? In such a scenario ... the code provided will not work. But I suggest to include it in a logon user powershell script.
Find elsewhere
🌐
Microsoft Learn
social.technet.microsoft.com › Forums › ie › en-US › 5cb1bf92-0f1a-4169-a72f-d2a9e40ac432 › username-variable-in-powershell
%username% variable in Powershell - Microsoft TechNet
November 15, 2021 - get-childitem -path \ums4455\env:USERNAME -recurse -filter cache ... So, for a better understanding ... you run a scheduled task with a dedicated account from a member server or whatever to cleanup a share ? The task is running directly on windows server hosting files or remotely on the share ? In such a scenario ... the code provided will not work. But I suggest to include it in a logon user powershell script.
🌐
Hosting Ultra So
hostingultraso.com › help › windows › view-modify-environment-variables-powershell
View and Modify Environment Variables in PowerShell | Windows PowerShell, Windows Server | HostingUltraso.com
The Target parameter defines where this variable should be stored: User for the current user, and Machine for all users on the machine. For example, to permanently add your Tools directory to your path:
🌐
Rene Nyffenegger
renenyffenegger.ch › notes › Windows › dirs › Users › username › index
%USERPROFILE%
A possible way to determine the path of a user's profile in PowerShell is like so: PS C:\> [System.Environment]::GetFolderPath([System.Environment+SpecialFolder]::UserProfile) C:\Users\Rene ... The cdhom.bat script takes one to this directory in cmd.exe. ... The combination of the environment variables HOMEDRIVE and HOMEPATH. The .NET enumeration System.Environment+SpecialFolder. The equivalent of a home directory in Linux is /home/<username>.
🌐
Microsoft Learn
learn.microsoft.com › en-us › answers › questions › 740046 › powershell-making-folder-using-env-username
Powershell - making folder using $env:username - Microsoft Q&A
Download Microsoft Edge More info about Internet Explorer and Microsoft Edge ... I´m new with Powershell and I have script, where I need to make folder using $env:username plus something else - for ex. username is David_N and I need to have folder David_N_Files · I can only make folder called $env:username Is it possible to make it with Powershell? ... Thank you very much. Works perfect ... Copy-Item -Path "$env:USERPROFILE\AppData\Local\Microsoft\Edge\User Data\Default\Bookmarks" -Destination "C:\Temp$($env:USERNAME)\Edge"
🌐
PowerShell Forums
forums.powershell.org › powershell help
Variables in a Path? - PowerShell Help - PowerShell Forums
June 22, 2015 - This works fine when I have the ... C:\Users\username\AppData\Roaming\Mitel\UC\username@wbbsmd.co.uk\user.config Is there a way to use the %username% variable in $Path to replace the username part of th......
🌐
PowerShell Forums
forums.powershell.org › powershell help
How to access access a path in \AppData\Local without a variable ? - PowerShell Help - PowerShell Forums
February 19, 2021 - Hi All Can anyone please tell me how to access/ write to the below path without using an environmental variable ? C:\Users\logged in user\AppData\Local The reason for this is it will be deployed via a scheduled task…and doing it that way does not allow the environmental variables…ie script ...
🌐
ITPro Today
itprotoday.com › home › powershell
Accessing environment variables in PowerShell
November 29, 2024 - Even shorter is gc env:username, which uses another alias ("gc") for Get-Content. By the way, the drive name here is ENV. You only add the colon when you're referencing the drive as part of a path, such as in the CD or DIR example. The second technique is even easier. PowerShell sports a built-in variable, $env, which accesses the environment variable store.
🌐
Reddit
reddit.com › r/powershell › get userprofile path for current logged in user.
r/PowerShell on Reddit: Get userprofile path for current logged in user.
May 28, 2021 -

Hello Powershellers

In my current environment, there are several users who’s profile folder name is different than their username due to AD changes. So I’m looking for a way to find the profile path of the logged in user and I can’t necessarily rely on the username. The other twist is that the power shell script is run by third party software and I’m not sure which service it runs as because $env:Userprofile variable doesn’t work when using the software. Any other ideas on how I can do this? My end goal is to copy a shortcut that is under a users profile to the startup folder.

🌐
Adam the Automator
adamtheautomator.com › powershell-environment-variables
PowerShell Environment Variables: A Deep Dive
The value type is REG_EXPAND_SZ and the value contains the %USERPROFILE% environment variable. If you’d rather use PowerShell to retrieve the registry value, you can so using the Get-Item cmdlet as shown below.
Published   October 1, 2023