#Function: Disabale users who have not logged in more than 180 days
#Author: Junson142099
#Last Updated Date: July 7, 2021
#Search and disable users that have not been connected to AD for more than 180 days
echo 'Please make sure you are running this script as administrator!'
Import-Module ActiveDirectory
#Export a list to a text document
$x = Split-Path -Parent $MyInvocation.MyCommand.Definition
$curDateTime = Get-Date -Format yyyyMMdd-HHmmss
Get-ADUser -properties lastLogonDate -filter {enabled -eq "True"} -SearchBase "ou=users,ou=shenzhen,dc=junson,dc=com" | where { $_.lastLogonDate -lt (get-date).addmonths(-6)} | Out-File $x\DisableUsers$curDateTime.txt -NoClobber -Encoding Default
$yesNo = Read-Host -prompt 'Please find DisableUsers.txt and confirm that all the users in the list is what you want to disable, do you want to continue? Y/N: '
if ($yesNo -eq 'y'){
#Disable users in the list
#If you need to exclude some computers, you can add {-and name -ne "XXXUSER"} in the filter.
Get-ADUser -properties lastLogonDate -filter {enabled -eq "True"} -SearchBase "ou=users,ou=shenzhen,dc=junson,dc=com" | where { $_.lastLogonDate -lt (get-date).addmonths(-6)} | Disable-ADAccount
echo 'Disable completed!'
pause
Exit
}else{
echo 'Cancelled!'
pause
Exit
}
#Function: Disabale computers which have not logged in more than 90 days
#Author: Junson142099
#Last Updated Date: July 7, 2021
#Search and disable computers that have not been connected to AD for more than 90 days
echo 'Please make sure you are running this script as administrator!'
Import-Module ActiveDirectory
#Export a list to a text document
$x = Split-Path -Parent $MyInvocation.MyCommand.Definition
$curDateTime = Get-Date -Format yyyyMMdd-HHmmss
Get-ADComputer -properties lastLogonDate -filter {enabled -eq "True"} -SearchBase "ou=computers,ou=shenzhen,dc=junson,dc=com" | where { $_.lastLogonDate -lt (get-date).addmonths(-3)} | Out-File $x\DisableComputers$curDateTime.txt -NoClobber -Encoding Default
$yesNo = Read-Host -prompt 'Please find DisableComputers.txt and confirm that all the computers in the list is what you want to disable, do you want to continue? Y/N: '
if ($yesNo -eq 'y'){
#Disable computers in the list
#If you need to exclude some computers, you can add {-and name -ne "XXXPC"} in the filter.
Get-ADComputer -properties lastLogonDate -filter {enabled -eq "True"} -SearchBase "ou=computers,ou=shenzhen,dc=junson,dc=com" | where { $_.lastLogonDate -lt (get-date).addmonths(-3)} | Disable-ADAccount
echo 'Disable completed!'
pause
Exit
}else{
echo 'Cancelled!'
pause
Exit
}
脚本使用说明:
目的:此脚本的目的是为了禁用AD上那些距离上次登录超过180天的用户和超过90天的计算机账户。
1、先编辑脚本,修改你想查询和禁用的ou范围,现在以我的测试服务器为例,请务必保证两处的ou范围是一致的,否则导出的列表和实际禁用的账户可能会不一致。
2、在AD上以管理员方式运行此脚本,会自动生成一个txt文件,里面记录了本次查找出距离最后一次登录的超过180天的用户。请确认此列表里的用户都是你想要禁用的,如确认输入y,脚本会自动禁用这些用户。否则请输入n,并回到第一步修改查询范围或添加排除范围。