Advertisement
warkaj

Force password change in Office 365 for expired on-premise

Aug 4th, 2017
1,106
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. ### Script to make Office 365 Users change password after on-premise AD account expiry ###
  2.  
  3. # Variables
  4. $AdminName = "<UPN of Account w/ permissions to execute>"
  5. $Pass = Get-Content "<C:\LocationOfTxtFile>" | ConvertTo-SecureString
  6. $cred = new-object -TypeName System.Management.Automation.PSCredential -ArgumentList $AdminName, $Pass
  7. # Set organizational unit searchbase and get users from on-premise AD with expired passwords and enabled accounts
  8. $ous = "<OU DN>","<OU DN>"
  9.  
  10.  
  11. # Load pshell modules for AD and MSOL, verify loaded
  12. Function Mod_LoadNLogin_MSOL
  13. {
  14. Import-Module ActiveDirectory                    # Imports AD Module
  15.     if (-not (Get-module activedirectory))
  16.         {
  17.         import-module activedirectory -Force     # Force import of AD Module
  18.         }
  19. Import-Module MSOnline                           # Imports Microsoft Online Module (Office 365)
  20.     if (-not (Get-module MSOnline))
  21.         {
  22.         import-module MSOnline -Force            # Force import MS Online Module
  23.         }
  24. Connect-MsolService -Credential $cred            # Connect to MSOnline w/ credentials supplied in variables
  25.   }
  26.  
  27. # Loop through OUs and populate $ADUser w/ AD user information
  28. # Data Type = List of ADUser objects
  29. $ADUser = foreach ($ou in $ous){
  30.     get-aduser -filter {(pwdlastset -eq "0") -and (enabled -eq $true)} -SearchBase $ou
  31.     #TODO; If $? -ne $True
  32.     }
  33.  
  34. # Iterate through on-premise users, find if they're licensed and when last password change
  35. ForEach ($i in $ADUser) {
  36.     $MSOLUser = Get-MsolUser -userprincipalname $i.UserPrincipalName  | select UserPrincipalName, isLicensed, LastPasswordChangeTimeStamp,@{Name=”PasswordAge”;Expression={(Get-Date)-$_.LastPasswordChangeTimeStamp}}  | Where-Object { $_.isLicensed -eq "TRUE" }
  37.     #Write-host $MSOLUser.UserPrincipalName $?
  38.     If (($? -eq $True) -and ($MSOLUser.UserPrincipalName -ne $null) -and ($MSOLUser.UserPrincipalName -ne '')){
  39.         Write-Host "we're going to do something with" $MSOLUser.UserPrincipalName
  40. ##### set O365 user to change pwd on next login
  41.         Set-MsolUserPassword -UserPrincipalName $MSOLUser.UserPrincipalName -ForceChangePasswordOnly $true -ForceChangePassword $true
  42.        #TODO; If $? -ne $True report error
  43.     }
  44. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement