Home > Net >  Powershell $env:username different outputs
Powershell $env:username different outputs

Time:10-21

I have a Powershell script that relies on the $env:username variable to distinguish file paths. However on several occasions (my script has to be run as admin) it picks up the Powershell Run As user rather than the logged on user.

Has anyone experienced this before or know a workaround. The bizarre thing is it seems to vary from machine to machine.

My script needs admin as it needs to delete files with sys permissions etc.

Thanks

CodePudding user response:

$env:USERNAME reflects the user identity of the current process.

Therefore, whether this value matches that of the user that logged on to the current OS session (window station) in an elevated (Run as adminstrator) process depends on what identity was used to launch it.

If a different account had to be used - in case the the logged-on user doesn't have permission to elevate him- or herself - $env:USERNAME will therefore differ from the logged-on user's username.

You can use the following command to get the logged-on user's username, irrespective of what account was used to start the calling PowerShell session:

(Get-CimInstance Win32_ComputerSystem).UserName
  • Related