I found it:

[Environment]::UserName
$Env:UserName

There is also:

$Env:UserDomain
$Env:ComputerName
Answer from Thomas Bratt on Stack Overflow
Discussions

Username variable in Powershell script
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, ... More on community.spiceworks.com
🌐 community.spiceworks.com
10
3
March 19, 2019
Powershell: Getting current logged on user - Programming & Development - Spiceworks Community
Ok, this is a little more difficult than the title makes it out to be. I know $env:username will get me the user. Unfortunately, that’s not the user I want to get when I’m in an elevated ps window. Basically I am using a logon script that starts a powershell process as another user. More on community.spiceworks.com
🌐 community.spiceworks.com
11
November 27, 2013
Using $env:USERNAME or other variables in a script.
There could be a couple of reasons: make sure you're using double quotes when using variables; single wires are considered literal strings and variables are not processed $name = 'Peter Piper' $title = "$name picked a peck of pickles" encapsulated complex variables and expressions within a string to have them evaluated in line "Right now it is $(Get-Date)" Try those and see if that is better. Also, if you leave just the string on a line, it will output its value and you can try that for debugging. More on reddit.com
🌐 r/PowerShell
10
1
June 14, 2022
Need to find the logged on user on windows 10 machine
Hi Team, i am using the below command to retreive the logged on user on win10 machine $userInfo = Get-WmiObject -Class Win32_ComputerSystem $($userInfo.UserName) The problem with this command is that it only retreives the console logon user and not the rdp user. is there any command which will ... More on forums.powershell.org
🌐 forums.powershell.org
3
0
March 29, 2024
🌐
Reddit
reddit.com › r/powershell › how to make my powershell script reference the current user account who is running it?
r/PowerShell on Reddit: How to make my powershell script reference the current user account who is running it?
September 26, 2022 -

Part of my script involves making yourself a site admin for OneDrive data (set-spouser), then adding the manager, then removing yourself. Since I've always been the only one using this script, I've hardcoded my username into the script. However, other people will be using this script.

When it comes to connecting to exchange online or other admin portals, it's easy to do. You just leave the -userprincipalname field empty, and you get a popup box asking to enter your username, then your password. How do you "leave empty" which account you want to make a site admin for OneDrive data?

🌐
SharePoint Diary
sharepointdiary.com › sharepoint diary › powershell › how to get the current user name in powershell?
How to Get the Current User Name in PowerShell? - SharePoint Diary
September 19, 2025 - Here’s how you can use the whoami query command in PowerShell to get the current user: ... This command returns the full logon name of the user, including the domain, in the format DOMAIN\Username.
🌐
MiniTool Partition Wizard
partitionwizard.com › home › partition manager › powershell get current username on windows 11/10/8/7 [full guide]
Advanced Guide: PowerShell Get Current Username on Windows
December 4, 2024 - The Windows Environment Variables can detect the username and logged-on user from your system via the following 3 methods. Way 1. Use Env PowerShell Drive · Type PowerShell in the search box, and then right-click the Windows PowerShell and select Run as administrator. Then click on Yes to confirm it. In the pop-up window, type the following command and hit Enter to get the current logged-on user name.
🌐
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, ...
Find elsewhere
🌐
Spiceworks
community.spiceworks.com › programming & development
Powershell: Getting current logged on user - Programming & Development - Spiceworks Community
November 27, 2013 - Ok, this is a little more difficult than the title makes it out to be. I know $env:username will get me the user. Unfortunately, that’s not the user I want to get when I’m in an elevated ps window. Basically I am usin…
🌐
Adam the Automator
adamtheautomator.com › powershell-get-current-user
Using the Dynamic PowerShell to Get Current Users
Using the Env: drive In PowerShell, get the current user by running the command below. ... The screenshot below shows the expected result. As you can see, the command returns the USERNAME item and its corresponding value, which is the currently logged-on user.
Published   October 6, 2022
🌐
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.

🌐
Delft Stack
delftstack.com › home › howto › powershell › powershell get current user
How to Get Current User in PowerShell | Delft Stack
February 2, 2024 - The Env: drive is automatically created when you start a PowerShell session. Because Env: is a drive, you may access its contents using the Get-ChildItem cmdlet, which works similarly to listing the items of a file system folder or drive. The user can be retrieved using the following command. ... In order to get the value only, the following command can be used. ... It can be seen the command returns the username value as a string.
🌐
ShellGeek
shellgeek.com › home › powershell tips › get current user name in powershell
Get Current User name in PowerShell - ShellGeek
April 14, 2024 - To get current user name in PowerShell, use whoami, GetCurrent() method of WindowsIdentity, $env or Get-WMIObject cmdlet in PowerShell.
🌐
Microsoft Learn
learn.microsoft.com › en-us › powershell › module › microsoft.powershell.localaccounts › rename-localuser
Rename-LocalUser (Microsoft.PowerShell.LocalAccounts) - PowerShell | Microsoft Learn
The Microsoft.PowerShell.LocalAccounts module is not available in 32-bit PowerShell on a 64-bit system. Rename-LocalUser -Name "Admin02" -NewName "AdminContoso02" This command renames the user account named Admin02.
🌐
PowerShell Forums
forums.powershell.org › powershell help
Need to find the logged on user on windows 10 machine - PowerShell Help - PowerShell Forums
March 29, 2024 - Hi Team, i am using the below command to retreive the logged on user on win10 machine $userInfo = Get-WmiObject -Class Win32_ComputerSystem $($userInfo.UserName) The problem with this command is that it only retreives…
🌐
Serveracademy
community.serveracademy.com › powershell
How to find User Logon Name by User Display Name in PowerShell - PowerShell - Server Academy Community Forum
May 3, 2022 - I have multiple display name of users in a csv file what should I do if I want to find their samaccount name and email address and from ad using PowerShell. and also a outcome if PowerShell cant find the user. we can do …
🌐
Powershell Commands
powershellcommands.com › powershell-username
Mastering PowerShell Username Commands Made Easy
July 4, 2024 - This command will return a list of users in your Active Directory, making it easier to manage usernames in a corporate environment. Understanding PowerShell Ternary for Quick Decisions
🌐
Microsoft
devblogs.microsoft.com › dev blogs › scripting blog [archived] › powertip: use a powershell command to get user name and domain
PowerTip: Use a PowerShell command to get User Name and Domain - Scripting Blog [archived]
June 26, 2013 - Summary: Use an easy command in Windows PowerShell to get userdomainusername. How can I use a command in Windows PowerShell to get information about a current user in userdomainusername format? Use the WhoAmI command: whoami
Top answer
1 of 3
1

You don't need all that.

Updated to include csv export.

$users = Import-Csv -path "C:\Users\Administrator\Desktop\Bulkload\Input.csv"  
$resultsArray = @()  
foreach ($user in $users) {  
    $firstname = $user.FirstName  
    $lastname = $user.LastName  
    $i = 1                        # pointer for first name   
    $LogonNameCounter = 0  
    $LogonNameSuffix = ""     # no trailing number while looping thru first name   
    While($true) {  
        $logonname = $firstname.substring(0, $i) + $lastname + $LogonNameSuffix  
        "Looking for $logonname"  
      
        # Call AD here  
        If ($(Get-ADUser -Filter {SamAccountName -eq $logonname})) {  
          "That account exists."   
            "Try the next name."  
        } else {  
            "That account does not exist."  
            " Use this name. Add it to the results."  
            $resultsArray += [PSCustomObject]@{  
                     FirstName=$user.FirstName;  
                     LastName=$user.LastName  
                     samAccountname=$logonname  
            }  
            break                   # exit this loop.  Maybe set a flag to indicate that how to proceed.   
        }  
                  
        if ($i -eq $firstname.Length) {  
            $logonNameCounter++   
            $LogonNameSuffix = $logonNameCounter  
        } else {  
            $i++   
        }  
        if ($logonNameCounter -gt 10) {  
            "We exceeded the max number to use. Something is wrong."  
            break                   # exit the while loop   
        }  
    }  
    "Done with this user."  
}   
$resultsArray | Export-Csv "C:\Users\Administrator\Desktop\Bulkload\Output-Result.csv"  


  
2 of 3
0

What's missing from the answer @MotoX80 posted, is what's not stated by you: Is it possible that accounts like "JohnSmith2" are already present in your AD?

If they do, then in addition to the answer from @MotoX80 , you'll have to start adding an incrementing value to the end of the account name you're trying to verify is not present once you reach the end of the user's first name, and start using just the users complete first and last names as the base.

Two other points:

  1. When you post code, please use the "Code Sample" editor. It's the icon with the "101 010" graphic (it's the 5th from the left on the format bar).
  2. If you're getting an exception, post the text of the error message. That will contain what the error is, and where in the script the error occurred.
🌐
FOG Project
forums.fogproject.org › topic › 10940 › windows-powershell-username-computername › 4
Windows (Powershell) / Username=Computername | FOG Project
October 17, 2017 - New-LocalUser $UserName -Password ... -Member $UserName · Thank you gentlemen! ... When you try to create a user with the same name as the Computername in command prompt, it will say that the two cannot be the same.