Add line to script to capture date script is ran

I would like to add the ability to log when this script was ran and what users were moved.

Import-Module ActiveDirectory

$disabledOU = "OU=InactiveUsers,DC=my,DC=domain,DC=com"

$users = Get-ADUser -Filter * -Properties SAMAccountName, lastLogonTimeStamp | ?{[DateTime]::FromFileTime($_.lastLogonTimeStamp) -lt (Get-Date).AddDays(-49)}
foreach ($user in $users)
{
    Disable-ADAccount -Identity $user.SAMAccountName -WhatIf
    Move-ADObject -Identity $user.SAMAccountName -TargetPath $disabledOU
}

Open in new window


Thank you!
LVL 9
samiam41Asked:
Who is Participating?
 
Dustin SaundersDirector of OperationsCommented:
Update $logPath to the directory to log output.

Logs will be stored as [Year]_[DayOfYear].log so the log file is always uniquely named.

Each line in the log file will be time stamped.

Again, haven't had a chance to test run (not in a good place to do so today) but this should accomplish that.
Import-Module ActiveDirectory

$logPath = "C:\Temp\"  #directory to log output
$date = Get-Date
$todaysLog = $logPath + $date.Year + "_" + $date.DayOfYear + ".log"

function WriteLog($message)
{
    $message = (Get-Date).ToShortTimeString() + " - " + $message
    Add-Content -Path $todaysLog -Value $message
}

$disabledOU = "OU=InactiveUsers,DC=my,DC=domain,DC=com"

$users = Get-ADUser -Filter * -Properties SAMAccountName, lastLogonTimeStamp | ?{[DateTime]::FromFileTime($_.lastLogonTimeStamp) -lt (Get-Date).AddDays(-49)}
foreach ($user in $users)
{
    try {
        Disable-ADAccount -Identity $user.SAMAccountName
        WriteLog("Disabled $($user.SAMAccountName)")
    } catch {
        WriteLog("Failed to disable $($user.SAMAccountName)")
    }
    
    try {
        Move-ADObject -Identity $user.SAMAccountName -TargetPath $disabledOU
        WriteLog("Moved $($user.SAMAccountName) to $disabledOU")
    } catch {
        WriteLog("Failed to move $($user.SAMAccountName) to $disabledOU")
    }
}

Open in new window

0
 
samiam41Author Commented:
Great work!  Thank you.
0
 
Dustin SaundersDirector of OperationsCommented:
No worries, happy to help.
1
 
samiam41Author Commented:
If you can help with my new question, I would appreciate it-> https://www.experts-exchange.com/questions/29072614/Stale-computer-script-PS.html#a42396563
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.