Unable to run script commands after connecting to Azure Ad

Sundaresan Chandrakanth 11 Reputation points
2021-06-23T09:33:20.883+00:00

hi

I am trying to run the below script to find out the list of users last password change date from current date and if that is more than 45 days, i wish to revoke their azure token sessions. But if i use this as script file, it is successfully connecting to Azure AD but never run any further commands beyond connecting it. This can be confirmed by giving $expiredusers command in the PowerShell which does not show any user list. If i remove out-null command from connect command, we can see the script just stops at connecting to azure ad and don't run the further commands.

What could be the issue?

$TenantId = "xxx"
$emailusername = "xxx@永爱不变 .com"
$encrypted = Get-Content C:\encrypted_password.txt | ConvertTo-SecureString
$UserCredential = New-Object System.Management.Automation.PsCredential($emailusername, $encrypted)

connect-msolservice -credential $UserCredential
connect-AzureAD -Tenantid $TenantID -Credential $UserCredential | Out-Null

$expiredusers= Get-MsolUser -All | Where-Object {$.PasswordNeverExpires -eq $false -and $.IsLicensed -eq $True -and $_.LastPasswordChangeTimestamp -lt (Get-Date).AddDays(-45)}
foreach($user in $expiredusers){
Get-AzureADUser -ObjectId $user.UserPRincipalName | Revoke-AzureADUserAllRefreshToken}
write-host "Tokens revoked"

Microsoft Entra ID
Microsoft Entra ID
A Microsoft Entra identity service that provides identity management and access control capabilities. Replaces Azure Active Directory.
19,852 questions
0 comments No comments
{count} vote

2 answers

Sort by: Most helpful
  1. Sundaresan Chandrakanth 11 Reputation points
    2021-06-23T12:08:49.05+00:00

    Hi Thanks for your reply..

    But the same command mentioned in my question, if i run manually after connecting to Azure AD, it works and captures the list inside the variable $expiredusers and displays the results.

    My issue is that when i automate this script unattended, the script stops after connecting to AZURE AD and never run the actual script commands from $expiredusers

    1 person found this answer helpful.
    0 comments No comments

  2. Vasil Michev 97,076 Reputation points MVP
    2021-06-23T12:05:47.04+00:00

    You have an error when creating said variable, $.PasswordNeverExpires and $.IsLicensed. Also, PasswordNeverExpires can have a Null value, which your if statement doesnt capture. Try something like this:

    Get-MsolUser -All | Where-Object {!$_.PasswordNeverExpires -and $_.IsLicensed -eq $True -and $_.LastPasswordChangeTimestamp -lt (Get-Date).AddDays(-45)}
    
    0 comments No comments