Skip Ribbon Commands
Skip to main content

Quick Launch

Todd Klindt's home page > Todd Klindt's Office 365 Admin Blog > Posts > How to Get the Microsoft 365 Connected User with PnP PowerShell
October 08
How to Get the Microsoft 365 Connected User with PnP PowerShell

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:

image 

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:

image 

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

image 

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:

image 

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

Comments

Thanks

Thank again for the wonderful work.
 on 7/12/2022 1:51 AM

Add Comment

Items on this list require content approval. Your submission will not appear in public views until approved by someone with proper rights. More information on content approval.

Title


Body *


Today's date *

Select a date from the calendar.
Please enter today's date so I know you are a real person

Twitter


Want a message when I reply to your comment? Put your Twitter handle here.

Attachments

 

 SysKit