-
Notifications
You must be signed in to change notification settings - Fork 32
/
Disable-InactiveADComputers.ps1
539 lines (448 loc) · 24.5 KB
/
Disable-InactiveADComputers.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
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
####################################################
#
# Title: Disable-InactiveADComputers
# Date Created : 2017-09-22
# Last Edit: 2018-02-14
# Author : Andrew Ellis
# GitHub: https://github.com/AndrewEllis93/PowerShell-Scripts
#
# Notes:
# This finds the last logon for all AD computers and disables any that have been inactive for X number of days (depending on what threshold you set).
# The difference with this script is that it gets the most accurate last logon available by comparing the results from all domain controllers. By default the lastlogontimestamp is only replicated every 14 days minus a random percentage of 5. This makes it much more accurate, but also it is a very slow. It also supports an exclusion AD group that you can put things like service computers in to prevent them from being disabled. It will also email a report to the specified email addresses.
# WARNING: THIS SCRIPT WILL OVERWRITE EXTENSIONATTRIBUTE3 FOR ALL COMPUTER OBJECTS, MAKE SURE YOU ARE NOT USING IT FOR ANYTHING ELSE
# This script is SLOW because it gets the most accurate last logon possible by comparing results from all DCs. By default the lastlogontimestamp is only replicated every 14 days minus a random percentage of 5.
#
####################################################
#Function declarations
Function Start-Logging {
<#
.SYNOPSIS
This function starts a transcript in the specified directory and cleans up any files older than the specified number of days.
.DESCRIPTION
Please ensure that the log directory specified is empty, as this function will clean that folder.
.EXAMPLE
Start-Logging -LogDirectory "C:\ScriptLogs\LogFolder" -LogName $LogName -LogRetentionDays 30
.LINK
https://github.com/AndrewEllis93/PowerShell-Scripts
.NOTES
Author: Andrew Ellis
#>
Param (
[Parameter(Mandatory=$true)]
[String]$LogDirectory,
[Parameter(Mandatory=$true)]
[String]$LogName,
[Parameter(Mandatory=$true)]
[Int]$LogRetentionDays
)
#Sets screen buffer from 120 width to 500 width. This stops truncation in the log.
$ErrorActionPreference = 'SilentlyContinue'
$pshost = Get-Host
$pswindow = $pshost.UI.RawUI
$newsize = $pswindow.BufferSize
$newsize.Height = 3000
$newsize.Width = 500
$pswindow.BufferSize = $newsize
$newsize = $pswindow.WindowSize
$newsize.Height = 50
$newsize.Width = 500
$pswindow.WindowSize = $newsize
$ErrorActionPreference = 'Continue'
#Remove the trailing slash if present.
If ($LogDirectory -like "*\") {
$LogDirectory = $LogDirectory.SubString(0,($LogDirectory.Length-1))
}
#Create log directory if it does not exist already
If (!(Test-Path $LogDirectory)) {
New-Item -ItemType Directory $LogDirectory -Force | Out-Null
}
$Today = Get-Date -Format M-d-y
Start-Transcript -Append -Path ($LogDirectory + "\" + $LogName + "." + $Today + ".log") | Out-Null
#Shows proper date in log.
Write-Output ("Start time: " + (Get-Date))
#Purges log files older than X days
$RetentionDate = (Get-Date).AddDays(-$LogRetentionDays)
Get-ChildItem -Path $LogDirectory -Recurse -Force | Where-Object { !$_.PSIsContainer -and $_.CreationTime -lt $RetentionDate -and $_.Name -like "*.log"} | Remove-Item -Force
}
Function Disable-InactiveADComputers {
<#
.SYNOPSIS
This script disables AD computers older than the threshold (in days) and stamps them in ExtensionAttribute3 with the disabled date. It also sends an email report.
.DESCRIPTION
Make sure you read through the comments (as with all of these scripts). It just finds the last logon for all AD computers and disables any that have been inactive for X number of days (depending on what threshold you set). The difference with this script is that it gets the most accurate last logon available by comparing the results from all domain controllers. By default the lastlogontimestamp is only replicated every 14 days minus a random percentage of 5. This makes it much more accurate. It also supports an exclusion AD group that you can put things like service computers in to prevent them from being disabled. It will also email a report to the specified email addresses.
"-ReportOnly" will skip actually disabling the AD computers and just send an email report of inactivity instead.
.EXAMPLE
Disable-InactiveADComputers -To @("email@domain.com","email2@domain.com") -From "noreply@domain.com" -SMTPServer "server.domain.local" -UTCSkew -5 -OutputDirectory "C:\ScriptLogs\Disable-InactiveADComputers" -ExclusionGroup @('ServiceComputers','Auto-Disable Exclusions') -DaysThreshold 30 -ReportOnly $True
.LINK
https://github.com/AndrewEllis93/PowerShell-Scripts
.NOTES
Author: Andrew Ellis
#>
Param(
#From address for email reports.
[Parameter(Mandatory=$true)]
[String]$From,
#If $true, email report will be sent without disabling or stamping any AD computers.
[switch]$ReportOnly = $False,
#SMTP server for sending reports.
[Parameter(Mandatory=$true)]
[String]$SMTPServer,
#Array. You can add more than one entry.
[Parameter(Mandatory=$true)]
[Array]$To,
#Accounting for the time zone difference, since some results are given in UTC. Eastern time is UTC-5.
[Parameter(Mandatory=$true)]
[Int]$UTCSkew,
#Threshold of days of inactivity before disabling the computer. Defaults to 30 days.
[Int]$DaysThreshold = 30,
#Where to export CSVs etc.
[Parameter(Mandatory=$true)]
[String]$OutputDirectory,
#Subject for email reports.
[String]$Subject = "Computer Cleanup Report",
#Amount of times to try for identical DC results before giving up. 30 second retry delay after each failure.
[Int]$MaxTryCount = 20,
#AD group containing computers to exclude.
[array]$ExclusionGroups
)
#Remove trailing slash if present.
If ($OutputDirectory -like "*\") {
$OutputDirectory = $OutputDirectory.substring(0,($OutputDirectory.Length-1))
}
#RE-ENABLED ACCOUNT FLAGGING
#Gets all AD computers with ExtensionAttribute3 set to an inactivity or disablement date and sets it to "RE-ENABLED ON "
Write-Output ""
Write-Output "RE-ENABLED ACCOUNT FLAGGING:"
Write-Output "Finding unflagged re-enabled computers..."
$ReEnabledComputers = Get-ADComputer -Filter * -Properties DistinguishedName,ExtensionAttribute3,SamAccountName,Enabled | Where-Object {
$_.Enabled -eq $True -and
(
$_.ExtensionAttribute3 -like "DISABLED ON*" -or
$_.ExtensionAttribute3 -like "INACTIVE SINCE*"
)
}
Write-Output (($ReEnabledComputers.SamAccountName.Count).ToString() + " computers were found.")
$Date = "RE-ENABLED ON " + (Get-Date)
ForEach ($ReEnabledComputer in $ReEnabledComputers){
Write-Output ("Setting ExtensionAttribute3 re-enabled flag for " + $ReEnabledComputer.SamAccountName + "...")
If ($ReportOnly){
Set-ADComputer -Identity $ReEnabledComputer.SamAccountName -Replace @{ExtensionAttribute3=$Date} -WhatIf
}
Else {
Set-ADComputer -Identity $ReEnabledComputer.SamAccountName -Replace @{ExtensionAttribute3=$Date}
}
}
#OLD RE-ENABLED ACCOUNT CLEANUP
#Gets all computers with ExtensionAttribute3 set to an expired re-enable date to clear it.
Write-Output ""
Write-Output 'CLEANUP - EXPIRED "RE-ENABLED" FLAGS:'
Write-Output 'Finding computers with expired "re-enabled" flags...'
$ExpiredFlagComputers = Get-ADComputer -Filter * -Properties DistinguishedName,ExtensionAttribute3,SamAccountName,Enabled | Where-Object {
$_.ExtensionAttribute3 -like "RE-ENABLED*" -and
[datetime]($_.ExtensionAttribute3 -replace 'RE-ENABLED ON ', '') -lt (Get-Date).AddDays(-$DaysThreshold)
}
Write-Output (($ExpiredFlagComputers.SamAccountName.Count).ToString() + " computers were found.")
ForEach ($ExpiredFlagComputer in $ExpiredFlagComputers){
Write-Output ("Clearing ExtensionAttribute3 re-enabled flag for " + $ExpiredFlagComputer.SamAccountName + "...")
If ($ReportOnly){
Set-ADComputer -Identity $ExpiredFlagComputer.SamAccountName -Clear ExtensionAttribute3 -WhatIf
}
Else {
Set-ADComputer -Identity $ExpiredFlagComputer.SamAccountName -Clear ExtensionAttribute3
}
}
#INACTIVE COMPUTER DISABLEMENT AND FLAGGING
#Declare try count at 0.
$TryCount= 0
#Get all DCs, add array names to vars array
$DCnames = (Get-ADGroupMember 'Domain Controllers').Name | Sort-Object
#This just tests if we already have results for each DC, in case we are running this twice in the same session (mostly just for testing).
$ExistingResults = @(0) * $DCnames.Count
$TestIteration = 0
$DCnames | ForEach-Object {
If (Get-Variable -Name $_ -ErrorAction SilentlyContinue){
$ExistingResults[$TestIteration] = $True
}
Else {
$ExistingResults[$TestIteration] = $False
}
$TestIteration++
}
#Check that results match from each DC by comparing all results in order. Retry if there is a mismatch, up to the MaxTryCount (default 20)
While (($ComparisonResults -contains $False -or !$ComparisonResults) -and $TryCount -lt $MaxTryCount){
#Makes sure we don't have any left over jobs from another run
Get-Job | Stop-Job
Get-Job | Remove-Job
If ((!$ExistingResults -or $ExistingResults -contains $False) -or ($ComparisonResults -contains $False -or !$ComparisonResults)){
#Fetch AD computers from each DC, add to named array
Write-Output ""
Write-Output "Starting data retrieval jobs..."
ForEach ($DCName in $DCnames) {
Start-Job -Name $DCName -ArgumentList $DCName -ScriptBlock {
param($DCName)
#Get AD results
Import-Module ActiveDirectory
$Results = Get-ADComputer -Filter {Enabled -eq $True} -Server $DCName -Properties DistinguishedName,LastLogon,LastLogonTimestamp,whenCreated,Description,ExtensionAttribute3 -ErrorAction Stop
$Results = $Results | Sort-Object -Property SamAccountName
Return $Results
}
}
#Wait for jobs to complete, show progress bar
Wait-JobsWithProgress -Activity "Retrieving and sorting results from each DC. Please be patient"
#Put results into named arrays for each DC
ForEach ($DCName in $DCnames) {
Set-Variable -Name $DCName -Value (Receive-Job -Name $DCName)
}
}
$ComparisonResults = @()
ForEach ($i in 0..(($DCnames.Count)-1)){
If ($i -le (($DCnames.Count)-2)){
Write-Output ("Comparing results from " + $DCnames[$i] + " and " + $DCnames[$i+1] + "...")
$NotEqual = Compare-Object (Get-Variable -Name $DCnames[$i]).Value (Get-Variable -Name $DCnames[$i+1]).Value -Property SamAccountName
If (!$NotEqual) {
$ComparisonResults += $True
}
Else {
$ComparisonResults += $False
}
}
}
If ($ComparisonResults -contains $False){
Write-Warning "One or more DCs returned differing results. This is likely just replication delay. Retrying..."
$TryCount++
}
}
If ($TryCount -lt $MaxTryCount){
Write-Output "All DC results are identical!"
}
Else {
Throw "Try limit exceeded. Aborting."
}
#Removes the completes jobs.
Get-Job | Remove-Job
#Convert our results into hash tables because they are MUCH faster to process than PSObjects.
If (!$ExistingResults -or $ExistingResults -contains $False){
Write-Output ""
Write-Output "Starting hash table conversions..."
Write-Output ""
ForEach ($DCName in $DCnames) {
[array]$Data = (Get-Variable -Name $DCName).Value
$Count = (Get-Variable -Name $DCName).Value.Count
Start-Job -Name $DCName -ArgumentList $Data,$Count -ScriptBlock {
param(
[array]$Data,
$Count
)
#Function to convert objects to hash tables
#Credit: https://gist.github.com/dlwyatt/4166704557cf73bdd3ae
Function ConvertTo-Hashtable{
[CmdletBinding()]
Param (
[Parameter(Mandatory = $true, ValueFromPipeline = $true)]
[psobject[]] $InputObject
)
Process{
ForEach ($object in $InputObject){
$hash = @{}
ForEach ($property in $object.PSObject.Properties){
$hash[$property.Name] = $property.Value
}
$hash
}
}
}
#Declare the results array with empty hash tables to put the hash table objects into.
[array]$HashResults = @(@{}) * $Count
#Loop through each object, convert to hash table, add to HashResults array.
$Iteration = 0
$Data | ForEach-Object {
$HashResults[$Iteration] = $_ | ConvertTo-Hashtable
$Iteration++
}
Return $HashResults
}
}
}
#Wait for jobs to complete, show progress bar
Wait-JobsWithProgress -Activity "Converting results to hash tables"
#Get the hash table results from the jobs.
If (!$ExistingResults -or $ExistingResults -contains $False){
ForEach ($DCName in $DCNames){
Set-Variable -Name $DCName -Value (Receive-Job -Name $DCName) -Force
}
}
#Get current time for comparison later.
$StartTime = Get-Date
#Computer count so we know how many times to loop.
$ComputerCount = (Get-Variable -Name $DCnames[0]).Value.Count
#Create results array of the same size
$FullResults = @($null) * $ComputerCount
#Loop through array indexes
ForEach ($i in 0..($ComputerCount -1)){
$ReEnabledDate = $null
#Grab computer object from each resultant array, make array of each computer object
$ComputerEntries = @(@{}) * $DCnames.Count
ForEach ($o in 0..($DCnames.Count -1)) {
$ComputerEntries[$o] = (Get-Variable -Name $DCnames[$o]).Value[$i]
}
#If that computer's array contains a mismatch, bail. This should realistically never happen because we already compared the arrays.
If (($ComputerEntries.SamAccountName | Select-Object -Unique).Count -gt 1){
Throw "A computer mismatch at index $i has occurred. Aborting."
}
#Find most recent LastLogon, whenCreated, and LastLogonTimestamps, cast to datetimes.
If ($ComputerEntries.LastLogon){
[datetime]$LastLogon = [datetime]::FromFileTimeUtc(($ComputerEntries.LastLogon | Measure-Object -Maximum).Maximum)
$LastLogon = $LastLogon.AddHours($UTCSkew)
[datetime]$TrueLastLogon = $LastLogon
}
Else {[datetime]$LastLogon = 0; $TrueLastLogon = 0}
[datetime]$whenCreated = $ComputerEntries[0].whenCreated
If ($ComputerEntries.LastLogonTimestamp){
[datetime]$LastLogonTimestamp = [datetime]::FromFileTimeUtc(($ComputerEntries.LastLogonTimestamp | Measure-Object -Maximum).Maximum)
$LastLogonTimestamp = $LastLogonTimestamp.AddHours($UTCSkew)
}
Else {[datetime]$LastLogonTimestamp = 0}
#If LastLogonTimestamp is newer, use that instead of LastLogon. Realistically this should never happen, but just in case.
If ($LastLogonTimestamp -gt $LastLogon){
$TrueLastLogon = $LastLogonTimestamp
}
#If there is no last logon available from any attributes, or it is older than 20 years (essentially null/zero), use the date created instead.
If ($TrueLastLogon -eq 0 -or !$TrueLastLogon -or (New-TimeSpan -Start $TrueLastLogon -End $StartTime).Days -gt 7300){
[datetime]$TrueLastLogon = $whenCreated
}
#If the account was flagged as re-enabled, take that into consideration too.
If ($ComputerEntries.ExtensionAttribute3 -like "RE-ENABLED ON*"){
$ReEnabledDate = [datetime](($ComputerEntries.ExtensionAttribute3 | Measure-Object -Maximum).Maximum -replace 'RE-ENABLED ON ', '')
If ($ReEnabledDate -gt $TrueLastLogon){
$TrueLastLogon = $ReEnabledDate
}
}
#Calculate days of inactivity.
$DaysInactive = (New-TimeSpan -Start $TrueLastLogon -End $StartTime).Days
#Create object for output array
$OutputObj = [PSCustomObject]@{
SamAccountName=$ComputerEntries[0].SamAccountName
Enabled=$ComputerEntries[0].Enabled
LastLogon=$TrueLastLogon
WhenCreated=$whenCreated
DaysInactive=$DaysInactive
Name=$ComputerEntries[0].Name
DistinguishedName=$ComputerEntries[0].DistinguishedName
Description=$ComputerEntries[0].Description
ReEnabledDate=$ReEnabledDate
}
#Append object to output array and output progress to console.
$FullResults[$i] = $OutputObj
$PercentComplete = [math]::Round((($i/$ComputerCount) * 100),2)
Write-Output ("Computer: " + $OutputObj.SamAccountName + " - Last logon: $TrueLastLogon ($DaysInactive day(s) inactivity) - $PercentComplete% complete.")
}
#Gets exlusions, error action is set to stop
If ($ExclusionGroups){
$ComputerExclusions = @()
ForEach ($ExclusionGroup in $ExclusionGroups){
Write-Output "Getting `"$ExclusionGroup`" members..."
$ComputerExclusions += (Get-ADGroupMember -Identity $ExclusionGroup -ErrorAction Stop).SamAccountName
}
}
#Filter
Write-Output "Filtering computers..."
$FilteredComputersResults = $FullResults | Where-Object {$ComputerExclusions -notcontains $_.SamAccountName}
$FullResults = $FullResults | Where-Object {$_ -ne $null}
#For some reason compare-object is not working properly without specifying all properties. Don't know why.
$ExcludedComputersResults = Compare-Object $FilteredComputersResults $FullResults `
-Property SamAccountName,enabled,lastlogon,whencreated,DaysInactive,name,distinguishedname,Description,ExtensionAttribute3 |
Select-Object SamAccountName,enabled,lastlogon,whencreated,DaysInactive,name,distinguishedname,Description,ExtensionAttribute3
#Add to ComputersDisabled array for CSV report. Also disable and stamp computers if ReportOnly is set to false (default).
$InactiveComputersDisabled = @()
If (!$ReportOnly){
$FilteredComputersResults | ForEach-Object {
If ($_.DaysInactive -ge $DaysThreshold){
Write-Output ("Disabling " + $_.SamAccountName + "...")
Disable-ADAccount -Identity $_.SamAccountName
$Date = "INACTIVE SINCE " + $_.LastLogon
Set-ADComputer -Identity $_.SamAccountName -Replace @{ExtensionAttribute3=$Date}
$InactiveComputersDisabled += $_
}
}
}
Else {
$FilteredComputersResults | ForEach-Object {
If ($_.DaysInactive -ge $DaysThreshold){
Write-Output ("Disabling " + $_.SamAccountName + "...")
Disable-ADAccount -Identity $_.SamAccountName -WhatIf
$Date = "INACTIVE SINCE " + $_.LastLogon
Set-ADComputer -Identity $_.SamAccountName -Replace @{ExtensionAttribute3=$Date} -WhatIf
$InactiveComputersDisabled += $_
}
}
}
#Filtered computers - add to ComputersNotDisabled array for CSV report
$ExcludedInactiveComputers = @()
$ExcludedComputersResults | ForEach-Object {
If ($_.DaysInactive -ge $DaysThreshold){
$ExcludedInactiveComputers += $_
}
}
#Create output directory if it does not exist
If (!(Test-Path $OutputDirectory)){
New-Item -ItemType Directory $OutputDirectory
}
#Form the paths for the output files
$InactiveComputersDisabledCSV = $OutputDirectory + "\InactiveComputers-Disabled.csv"
$InactiveComputersExcludedCSV = $OutputDirectory + "\InactiveComputers-Excluded.csv"
#Export the CSVs
$InactiveComputersDisabled | Export-CSV $InactiveComputersDisabledCSV -NoTypeInformation -Force
If ($ExclusionGroups){
$ExcludedInactiveComputers | Export-CSV $InactiveComputersExcludedCSV -NoTypeInformation -Force
}
#Send email with CSVs as attachments
Write-Output "Sending email..."
If ($ExclusionGroups){
$ExclusionGroupsList = $ExclusionGroups -join ", "
$Body = @"
Attached are two reports:
- InactiveComputers-Disabled.csv: AD computers that were disabled for inactivity ($DaysThreshold days).
- InactiveComputers-Excluded.csv: Inactive AD computers that were excluded from disablement.
Excluded AD group(s): $ExclusionGroupsList
"@
}
Else {
$Body = "Attached is a list of AD computers that were disabled for inactivity ($DaysThreshold days)."
}
If ($ExclusionGroups) {
Send-MailMessage -Attachments @($InactiveComputersDisabledCSV,$InactiveComputersExcludedCSV) -From $From -SmtpServer $SMTPServer -To $To -Subject $Subject -Body $Body
}
Else {
Send-MailMessage -Attachments @($InactiveComputersDisabledCSV) -From $From -SmtpServer $SMTPServer -To $To -Subject $Subject -Body $Body
}
<#
# This is here if you want to use it in conjunction with my Move-Disabled script. Just uncomment and replace with your scheduled task path.
Write-Output "Starting Move-Disabled task..."
Start-ScheduledTask -TaskName "\Move-Disabled"
#>
}
Function Wait-JobsWithProgress {
param(
[Parameter(Mandatory=$true)]
[string]$Activity
)
# SHOW JOB PROGRESS
$Total = (Get-Job).Count
$CompletedJobs = (Get-Job -State Completed).Count
# Loop while there are running jobs
While ($CompletedJobs -ne $Total) {
# Update progress based on how many jobs are done yet.
# Write-Output "Waiting for background jobs: $CompletedJobs/$Total"
Write-Progress -Activity $Activity -PercentComplete (($CompletedJobs/$Total)*100) -Status "$CompletedJobs/$Total jobs completed"
# After updating the progress bar, get current job count
$CompletedJobs = (Get-Job -State Completed).Count
}
Write-Progress -Activity $Activity -Completed
}
#Start logging.
Start-Logging -LogDirectory "C:\ScriptLogs\Disable-InactiveADComputers" -LogName "Disable-InactiveADComputers" -LogRetentionDays 30
#Start function.
. Disable-InactiveADComputers -To @("email@domain.com","email2@domain.com") -From "noreply@domain.com" -SMTPServer "server.domain.local" -UTCSkew -5 -DaysThreshold 60 -OutputDirectory "C:\ScriptLogs\Disable-InactiveADComputers" -ExclusionGroup @("ServiceAccts") -ReportOnly
#Stop logging.
Write-Output ("Stop time: " + (Get-Date))
Stop-Transcript