-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDisableOldComputersInAD.ps1
34 lines (33 loc) · 2.12 KB
/
DisableOldComputersInAD.ps1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
Import-Module ActiveDirectory
$smtpServer = "ex.lab.local"
$fromAdress = "[email protected]"
$toAdress = "[email protected]"
$limit = (Get-Date).AddDays(-90)
$warningLimit = (Get-Date).AddDays(-70)
$logfileForOldComputers = "C:\Temp\" + (get-date -Format yyyy-MM-dd) + "-DisabledComputers.txt"
$logfileForComputersThatWillBeDeactivatedSoon = "C:\Temp\" + (get-date -Format yyyy-MM-dd) + "-ComputersThatWillBeDeactivatedSoon.txt"
$OldComputers = Get-ADComputer -Properties LastLogonDate -Filter { LastLogonDate -lt $limit -and Enabled -eq $true }
$SoonOldComputers = Get-ADComputer -Properties LastLogonDate -Filter { LastLogonDate -lt $warningLimit -and Enabled -eq $true }
if ($OldComputers.count -gt 0) {
New-Item -ItemType File -Path $logfileForOldComputers -Force
}
if ($SoonOldComputers.count -gt 0) {
New-Item -ItemType File -Path $logfileForComputersThatWillBeDeactivatedSoon -Force
}
foreach ($item in $OldComputers) {
Disable-ADAccount -Identity $item.SamAccountName
"The Computer " + $item.SamAccountName + " is now disabled." | Out-File $logfileForOldComputers -Append
}
foreach ($item in $SoonOldComputers) {
$diff = NEW-TIMESPAN –Start $limit –End $item.LastLogonDate
"The Computer " + $item.SamAccountName + " will be disbaled in " + $diff.Days + " Days" | Out-File $logfileForComputersThatWillBeDeactivatedSoon -Append
}
if ($OldComputers.count -gt 0 -or $SoonOldComputers.count -gt 0) {
Send-MailMessage -SmtpServer $smtpServer -Subject "Disbale old Cupmters in AD" -Attachments $logfileForOldComputers,$logfileForComputersThatWillBeDeactivatedSoon -To $toAdress -From $fromAdress -body "Please be sure to check!" -Encoding UTF8
}
elseif ($OldComputers.count -gt 0) {
Send-MailMessage -SmtpServer $smtpServer -Subject "Disbale old Cupmters in AD" -Attachments $logfileForOldComputers -To $toAdress -From $fromAdress -body "Please be sure to check!" -Encoding UTF8
}
elseif ($SoonOldComputers.count -gt 0) {
Send-MailMessage -SmtpServer $smtpServer -Subject "Disbale old Cupmters in AD" -Attachments $logfileForComputersThatWillBeDeactivatedSoon -To $toAdress -From $fromAdress -body "Please be sure to check!" -Encoding UTF8
}