Obtaining current user information in PowerShell Server.



Depending on your PowerShell Server settings sometimes getting session user information from the server might return unexpected results. For example if you are running your server as a service where “Isolated Sessions” are disabled, making the call:

PS> [Environment]::GetEnvironmentVariable("UserName")

or

PS> $env:UserName

or

PS> whoami

May return the Machine name instead of the expected Username. The reason for this is that both of those calls check environment variables which may or may not have information on your particular session depending on server settings. Instead use:

PS> [Environment]::UserName

This will call the the GetUserName() api, which is aware of your particular session and will return the current user even when Impersonation is active.