LastWriteTime for files

I have a script which sends an email with a file count for a specific folder on each server. I need to modify it to only count files OLDER than 1 day.

$myfile = “c:\downloads\auditserverList.csv”
$ServerList = Get-Content $myfile

$reportData = Invoke-Command -ErrorAction Continue -ComputerName $ServerList -ScriptBlock {
    [pscustomobject]@{
###line below is what I am trying to edit. filter isn't working
        FileCount =  (get-childitem c:\auditLogs -filter "LastWriteTime -lt (Get-Date).AddDays(-1)" | measure-object).count
                     }
                                                      } 

According to the docs, the -filter parameter qualifies the path parameter so I don’t think you can filter it that way. You can pipe to where-object to accomplish what you are trying to do.

FileCount =  (get-childitem c:\auditLogs | Where-Object LastWriteTime -lt (Get-Date).AddDays(-1) | measure-object).count
2 Likes

I use (Do-Something).Property in similar cases which seems to speed response times, but I’ve yet to measure it against Where-Object. Below, I put the new files count inside a dictionary object in case each item needs to be called separately (may still be called in whole); the key MyServer would be replaced by the name of current server instance.

Code

$newFilesCount = [System.Collections.Generic.Dictionary[string,string]]::new();
$newFilesCount.Add("MyServer",(((Get-ChildItem C:\AuditLogs).LastWriteTime) -lt (Get-Date).AddDays(-1)).Count);
#demos
$newFilesCount;
echo '';
$newFilesCount.Keys;
$newFilesCount["MyServer"];

Thanks Dicey! Ralphmwr pointed out the solution. But I’ll catalog your code for future use.
-KevinS

1 Like

Awesome! I hadn’t seen the Solution flag earlier.
-d