Share via


Powershell Script for Checking which files have not been accessed in the last 30 days and then email the user about it!

I am only beginning my journey in powershell so and i was presented with a challenge the other day to find files and report on the that have not been accessed within a certain number of days... so i decided what better way to learn then on the job!

This script will check the users home directory attribute, browse the directory for files that have not been accessed in 30 days and then create a report and send an email to the user…

comments welcome on how to make it better…

******************************************************************************************************

import-module ActiveDirectory
write-host "Checking For HomeDirectory Attribute…."
$enabledusers = get-aduser -filter {Enabled -eq "True"} -properties Homedirectory |where {$_.HomeDirectory -ne $null}

Foreach ($u in $enabledusers)
{
write-host "Current User…." $u.Name
write-host "You Home Directory is…" $u.HomeDirectory
$pathtocheck = $u.homedirectory

$statuscheck = get-childitem $pathtocheck -Recurse

Foreach ($s in $statuscheck)

{

$access = $s | % {(get-date) – $_.LastAccessTime }
if ($access.days -ge 2)
{
#write-host $s.fullname
#write-host "File Was Last Accessed" $access.days "Days Ago"

$outputfilename = ( "c:\" + $u.samaccountname + "30dayReport.csv")
#$outputfilename
$s |format-table -property Fullname |out-file $outputfilename -append
$attachment = $outputfilename
}

}

$emailto = ("<" + $u.samaccountname + "@test.com>")
$emailfrom = "<admin@test.com>"
$smtpserver = "dc-01.contoso.local"

Write-host "Sending Report….."
send-mailmessage -to $emailto -from $emailfrom -subject "warning you have files which have not been accessed in over 30days" -smtpserver $smtpserver -attachment $attachment

*********************************************************************************************************