Microsoft Graph in PowerShell, Get-MgUser -Select multiple user properties

Viewed 1572

I'm working on a script to deactivate inactive users in our Azure AD environment, I have the authentication stage down I'm just having issues parsing through the data correctly to get what I need.

Using the Microsoft.Graph.Users CMDLET, I can get user info from our directory with Get-MgUser command, but cannot -Select more than one attribute.

$Users = Get-MgUser -Top 10 -Select SignInActivity, UserPrincipalName | Select -ExpandProperty SignInActivity

This allows me to select the SignInActivity and expand it to see the LastSignInDateTime property but I cannot also select the UserPrincipalName property. And the following using -Filter doesn't find the SignInActivity property but finds the UserPrincipalName

$Users = Get-MgUser -Top 10 | Format-List SignInActivity, UserPrincipalName | Select -ExpandProperty SignInActivity

Edit to show outputs: My expected output is along the lines of:

UserPrincipalName : user@agency.com 
LastSignInDateTime : 10/28/2021 12:10:41 AM

What I'm getting from the first command is just:

LastSignInDateTime : 1/9/2021 2:54:49 AM

And the second command is:

Property "SignInActivity" cannot be found.

1 Answers

I have tested in my environment

You can use the below script to get the desired output:

$Result=@()
$usersUPN = Get-MgUser -Top 10 | Select  UserPrincipalName, ID
foreach($user in $usersUPN)
{
    $usersignindate = Get-MgUser -UserId $user.ID -Select SignInActivity | Select -ExpandProperty SignInActivity
    $userprops = [ordered]@{
        UserPrincipalName = $user.UserPrincipalName
        LastSignInDateTime = $usersignindate.LastSignInDateTime
    }
    $userObj =  new-object -Type PSObject -Property $userprops
    $Result += $userObj
}
$Result 

enter image description here

Related