#requires -Version 5.1 <# .SYNOPSIS Counts files whose last-write time or filename date falls on the selected day. .DESCRIPTION Date defaults to today. The selected day runs from local midnight (inclusive) to the next midnight (exclusive). Any time component in Date is ignored. DateString reads yyyyMMdd, yyyy-MM-dd, or yyyy_MM_dd from the filename. An optional HHmm or HHmmss suffix is accepted and ignored. Only the count is written to standard output. Errors stop the script. Only files directly inside FolderPath are searched. Filter is a filename pattern. .EXAMPLE .\FileNumMonitor.ps1 -MonitorType LastWriteTime -FolderPath C:\BACKUP -Filter 'backup-*.zip' .EXAMPLE .\FileNumMonitor.ps1 -MonitorType DateString -FolderPath C:\BACKUP -Filter 'backup-*.zip' .EXAMPLE .\FileNumMonitor.ps1 -MonitorType DateString -FolderPath C:\BACKUP -DaysOffset -1 .EXAMPLE .\FileNumMonitor.ps1 -MonitorType DateString -FolderPath C:\BACKUP -DaysOffset -2 -TimeSpan 2 #> [CmdletBinding()] param( [ValidateSet('LastWriteTime', 'DateString')] [string]$MonitorType = 'LastWriteTime', [Parameter(Mandatory = $true)] [ValidateNotNullOrEmpty()] [string]$FolderPath, [ValidateNotNullOrEmpty()] [ValidatePattern('^[^\\/:]+$')] [string]$Filter = '', # Days relative to today: 0 = today, -1 = yesterday. [int]$DaysOffset = 0, [ValidateRange(1, 2147483647)] [int]$TimeSpan = 1 ) $ErrorActionPreference = 'Stop' $DaysOffset = -[Math]::Abs($DaysOffset) $StartDate = [datetime]::Today.AddDays($DaysOffset) $EndDate = $StartDate.AddDays($TimeSpan) $directory = Get-Item -LiteralPath $FolderPath if (-not $directory.PSIsContainer -or $directory.PSProvider.Name -ne 'FileSystem') { throw 'FolderPath must identify a file-system directory.' } [long]$count = 0 Get-ChildItem -LiteralPath $directory.FullName -Filter $Filter -File | ForEach-Object { $file = $_ if ($MonitorType -eq 'LastWriteTime') { if ($file.LastWriteTime -ge $StartDate -and $file.LastWriteTime -lt $EndDate) { $count++ } } else { # Match a calendar date; an optional four- or six-digit time is ignored. $datePattern = '(?\d{8}|\d{4}-\d{2}-\d{2}|\d{4}_\d{2}_\d{2})(?:\d{6}|\d{4})?(?!\d)' foreach ($match in [regex]::Matches($file.BaseName, $datePattern)) { $timestamp = [datetime]::MinValue $valid = [datetime]::TryParseExact( $match.Groups['date'].Value, [string[]]@('yyyyMMdd', 'yyyy-MM-dd', 'yyyy_MM_dd'), [System.Globalization.CultureInfo]::InvariantCulture, [System.Globalization.DateTimeStyles]::None, [ref]$timestamp ) if ($valid -and $timestamp -ge $StartDate -and $timestamp -lt $EndDate) { $count++ break } } } } $count