次の方法で共有


Finding the UserID from a PowerShell Remoting session

A colleague presented a challenge to me the other day which I thought was "do able" but I'd never thought about it before.

"A set of user Credentials are in use in an Implicit Remoting Session, the authentication has been performed interactively by a web site.... We won't know who the user is but the client would like to trap the LoginID per session for logging purposes.   Could we?"

I said to give me a few minutes to poke at it.    I received a picture of "Pokey" from "Gumby and Pokey" as a response.   I love the humor around here.

I did the connection and followed the process to create the implicit remoting session as indicated.   I remembered that if I exported the PowerShell session as a module I could reuse, it always remembered at LEAST the login ID.   I tried that first

Export-PSsession -session $s -outputmodule test

I pulled open the PSM1 file and examined it for the login ID I used.   Sure enough it was embedded.

"Somewhere.... this object is stored in the session...."

But where?

First we grab the current sessions

$S=Get-PsSession

Now we have a list.  In this case I need to grab the credentials from an Exchange Session.   I can filter on that in the following manner.

$S=(Get-PSSession | Where { $_.ConfigurationName -eq 'Microsoft.Exchange' })

Now that I have the session I was able to pull up a Get-Member and found the "Runspace" object.     I started digging deeper and found an additional property called "ConnectionInfo"

Suddenly this all seemed possible.   "ConnectionInfo" had some additional objects, but most importantly …. "Credential"

So at this point it was a matter digging in an grabbing that username object off Credential as you would normally do before.

$UserName=$S.Runspace.Connectioninfo.Credential.Username

Now the cool part is all PowerShell Sessions work this way.  Direct, Implicit.... Even with an MFA setup you should be able to pull the UserID out in this fashion!

Just remember, the Power of Shell is in YOU

Sean
The EnergizedTech
Microsoft PFE