I need a script that should move disabled user accounts from their respective OU's to disabled accounts OU. Those disabled accounts should be at least 7 days old. I also want that if any of the Disabled user accounts is member of security group ""DNM_users" it should not be moved.
I have somehow manged to draft the following script which is moving the user accounst but it also moving the user accounts which are part of "DNM_users " security group which i dont want to happen.
I am not sure on how this memberof cmdlet works so kindly help me out in getting this output correct.
# script that will search for disabled accounts which will be moved to DisabledAccount OU
# PROCESS STEPS:
# 1. SEARCH users from Contoso/Users OU with following conditions
# - User's lastModifiedDate is older than 7 days
#- User are already disabled
#- Users must not be part of security group "DNM_Users"
# 2. MOVE found DISABLED users to DisabledAccounts OU
# LOAD AD POWERSHELL MODULE
import-module activedirectory
# VARIABLES FOR PATHS, ETC...
$tooold = (Get-Date).AddDays(-7)
$oldpath = "OU=Users,DC=contoso,DC=com"
$newpath = "OU=DisabledAccounts,DC=contoso,DC=com"
$logpath = "D:\housekeeping\Logs\DISABLED-USERS"
$date = get-date -format d-M-yyyy
# THIS IS THE SEARCH PART
$oldusers = Get-ADuser -Searchbase $oldpath -Property Name,Description,whenChanged,DistinguishedName -Filter {(Enabled -eq $False) -and (modified -le $tooold) -and (memberof -ne "DNM_users")}
# THIS WILL CREATE LOG FILE OF FOUND USERS
$howmany = ($olduers).count
$oldusers | Select Name,Description,whenChanged,DistinguishedName | export-csv $logpath\"$date"_DISABLED_"$howmany"_users.txt
# THIS IS EXECUTION PART THAT WILL MOVE DISABLED USERS TO DISABLEDACCOUNTS OU
$olduers | move-ADobject -targetPath $newpath