I did a webcast today about automating management of the datacenter with group policies and scripts. It was in Swedish, but I’ll make a blog series in English and share that information with all of you.
One of the attendees asked for the quick-and-dirty script I’ve scheduled to disable inactive computer-accounts. Here it is.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
import-module ActiveDirectory Search-ADAccount -ComputersOnly -AccountInactive -TimeSpan 0.00:00:00 | where Enabled -eq $true | where Name -notlike CL* | ForEach-Object { $olddesc = (Get-ADComputer -Identity $_ -Prop description).Description disable-adaccount $_ set-adcomputer $_ -Description "Account disabled $(Get-Date -format "yyyy-MM-dd") by System. $olddesc" move-adobject $_ -targetpath "OU=OldAccounts,OU=Server,OU=Cloud,DC=cloud,DC=truesec,DC=com" } Search-ADAccount -ComputersOnly -AccountInactive -TimeSpan 30.00:00:00 | where Enabled -eq $true | ForEach-Object { $olddesc = (Get-ADComputer -Identity $_ -Prop description).Description disable-adaccount $_ set-adcomputer $_ -Description "Account disabled $(Get-Date -format "yyyy-MM-dd") by System. $olddesc" move-adobject $_ -targetpath "OU=OldAccounts,OU=Server,OU=Cloud,DC=cloud,DC=truesec,DC=com" } |
I’ve scheduled it to run with a Scheduled Task deployed in a GPO that only applies to the PDC Emulator, so all DC’s doesn’t run the script.
Hi Les,
By using just this query, you can find out which machines it would detect and set to disabled if the rest of the script would run;
Search-ADAccount -ComputersOnly -AccountInactive -TimeSpan 0.00:00:00 | where Enabled -eq $true
Microsoft has some documentation here around that command and the Switches;
https://technet.microsoft.com/en-us/library/ee617247.aspx
In our environment, we want to remove all inactive accounts that does not follow our naming standard CL**** at once, while we let computers that follow the naming standard stay longer.
But just play around with the -TimeSpan value to find your sweetspot.
Thank you Markus,
I have been looking for just such a script for a while now, and almost all others I have been able to decipher what they are supposed to be doing, however none have worked correctly in my environment. (the last one disabled ALL computer accounts!!!)
My PowerShell knowledge is new and very basic. Can you explain what each search query is doing?
Search-ADAccount -ComputersOnly -AccountInactive -TimeSpan 0.00:00:00
Is this searching for accounts that have NOT been inactive?
If they have been inactive for a timespan of 0.00:00:00 would you want to disable them?
The second Search-ADAccount seems to search for accounts that have been inactive for 30 days, which makes sense to me.
Please point out what I must be misunderstanding.
Thank you,
LT