How do I get username in WinRM session?

Hello,

I have WinRM session configuration which specifies “RunAs” account. So when any account login with their credentials to remote session $env:UserName contains RunAs account instead of username of user who actually connected to end point. Is there any way to retrieve information about user who actually inititated the connection?

Not from within the session.

What I’ve done in the past is create proxy functions for a remote custom endpoint that uses a RunAs account which essentially writes to the event log with the user’s logon name and source computer prior to running the actual command. I use a custom Source in the event log so it can be easier to filter for. It does require a little more work up front, but can help with auditing later on down the road.
To be honest, if you are using a RunAs account (especially if it is an Administrator account that has access to multiple systems), you should be constraining that endpoint as best you can and giving only the commands that a user needs (even better as a proxy function) as this type of endpoint allows for the ‘double hop’ to hit remote systems from the server hosting the remote endpoint.

This still does not give you who logged in though, is not it? You write to event log RunAs account.

My apologies!
I went with what I had done in the past in creating a UI that interfaces with the remote constrained endpoint that utilizes some proxy functions with built-in auditing that writes to the event log whenever someone uses the utility. I didn’t think about if someone goes into the endpoint interactively or uses Invoke-Command. If that is the case, then there really isn’t a good approach to pulling the information. I think that if you are using a default endpoint that exists when you enable PSRemoting, then you can look at the Windows Remote Management logs and locate that information. If you are using a custom endpoint, then you are pretty much out of luck.

Am I missing something? This information is available inside $PSSenderInfo variable

[DNVIISADMIN2]: PS C:\Users\svcacct-manage\Documents> $PSSenderInfo

UserInfo : System.Management.Automation.Remoting.PSPrincipal
ClientTimeZone : System.CurrentSystemTimeZone
ConnectionString : http://dnviisadmin2:5985/wsman?PSVersion=4.0
ApplicationArguments : {PSVersionTable}
ConnectedUser : PROD\gsuvalian
RunAsUser : PROD\svcacct-manage

Perfect! You can use that info to write an event log or log file somewhere (event log would be best choice) and throw it in a startup script so it runs whenever someone connects to the remote endpoint.