Hi All,
I've written the following script to disable accounts that haven't logged onto in X number of days. It works a treat but I'm just adding some log output for when we have auditors / queries but I'm struggling to add the date that each account is disabled
Can anyone help:
This script is going to run on a daily basis, and I would like it to output to one file, in this case C:\disabledusers.csv. What I would like it to do however, before it writes the array to the csv, is to write todays date so I know from looking at the CSV, which accounts were disabled on that day.
ie.
or have it tagged on each line ie.
Can anyone help please?
I've written the following script to disable accounts that haven't logged onto in X number of days. It works a treat but I'm just adding some log output for when we have auditors / queries but I'm struggling to add the date that each account is disabled
Can anyone help:
Code:
Import-Module ActiveDirectory
function Get-ADUsersLastLogon()
{
$numberOfDays = (Get-Date).AddDays(-435)
$logDate = Get-Date -F dd-MM-yyyy
$logPath = "c:\DisabledUsers.csv"
$searchbase = "DC=company,DC=com"
$DisabledOU = "OU=Disabled Objects,DC=mystagecoach,DC=com"
$logArray = @()
$dcs = Get-ADDomainController -Filter {Name -like "*"}
$users = Get-ADUser -searchbase $SearchBase -Filter {((lastlogondate -le $numberOfDays) -AND (enabled -eq $True))}
$time = 0
foreach($user in $users)
{
foreach($dc in $dcs)
{
$hostname = $dc.HostName
$currentUser = Get-ADUser $user.SamAccountName | Get-ADObject -Server $hostname -Properties lastLogon
if($currentUser.LastLogon -gt $time)
{
$time = $currentUser.LastLogon
}
}
$time = 0
Disable-ADAccount $currentUser
Set-ADUser $currentUser -Description "Account disabled on $logDate"
Move-ADObject $currentUser -TargetPath $DisabledOU
#Create array for logfile output
$obj = $currentUser | Select Name,distinguishedname,@{n="status";e={'Disabled User'}}
#Output to Log
$logArray += $obj
}
#Export contents of logArray to .csv
$logArray | Export-Csv $logPath -NoTypeInformation
}
Get-ADUsersLastLogon
This script is going to run on a daily basis, and I would like it to output to one file, in this case C:\disabledusers.csv. What I would like it to do however, before it writes the array to the csv, is to write todays date so I know from looking at the CSV, which accounts were disabled on that day.
ie.
Code:
21/08/15
Joe Bloggs | CN=Joe Bloggs,OU=Users,DC=company ,DC=com | Disabled User
Tom Smith | CN=Tom Smith,OU=Users,DC=company ,DC=com | Disabled User
Code:
Name distinguishedname status
Joe Bloggs | CN=Joe Bloggs,OU=Users,DC=company ,DC=com | Disabled User | 21/08/15