As I’ve alluded to before, I spend a lot of time in PowerShell, and most of it in the loving embrace of the PnP.PowerShell module. From time to time I find myself wanting to include logic in my scripts based on who the script is being run as, who connected to Microsoft 365. The majority of my connections where with the good old username and password combination. When that’s the case, I could use this to find how who I had connected as:
Connect-PnPOnline -Url https://m365x995492.sharepoint.com/
admin@M365x995492.onmicrosoft.com
((Get-PnPConnection).PSCredential).username
It looks like this:
That worked great, right up to the point where I didn’t just log in with username credentials. For instance, the Sympraxis tenant requires MFA so I have to connect with the –Interactive parameter:
Old Faithful let me down. Back to the drawing board. Poking around the Internet I saw some smart folks were using this method:
$ctx = Get-PnPContext
$ctx.Load($ctx.Web.CurrentUser)
$ctx.ExecuteQuery()
$ctx.Web.CurrentUser
$UPN = $ctx.Web.CurrentUser.Email
I haven’t tried it yet with Certificate authentication, so I’m not sure how it reports that. The good news is that method also works with a username and password login:
I’ve created a Function, Get-TKPnPCurrentUser, to make that short and easy to use. I've added it to the TKM365Commands module I published in GitHub.
tk
ShortURL: https://www.toddklindt.com/POSHGetCurrentPnPUser
edit 4/15/22 - Added link to GitHub