Jerry1
Jerry1

Reputation: 372

Get files between two dates in PowerShell

I need to select files in a folder only between the first day in the current month and the last day in the current month. I tried:

$curr_month = (Get-Date -format "MM/01/yyyy 0:00:00")
$next_month = (Get-Date  $curr_moth).addmonths(1)
Get-ChildItem "\\logserver\C$\WINDOWS\SYSTEM32\LOGFILES\" -Recurse -include @("*.log") |
 where {$_.CreationTime -ge $curr_month -and
        $_.CreationTime -lt $next_month
        }

I get only the first log file and continue error:

Get-ChildItem : The specified network name is no longer available.

At line:3 char:18
+     Get-ChildItem <<<<  "\\logserver\C$\WINDOWS\SYSTEM32\LOGFILES\" -Recurse -include @("*.log") |
    + CategoryInfo          : ReadError: (\\logserver\C$\WI...ES\WMI\RtBackup:String) [Get-ChildItem], IOException
    + FullyQualifiedErrorId : DirIOError,Microsoft.PowerShell.Commands.GetChildItemCommand

The second problem: only from the first level of the path (no deep recursion).

Upvotes: 1

Views: 12356

Answers (1)

Oli
Oli

Reputation: 3536

$path = "\\logserver\C$\WINDOWS\SYSTEM32\LOGFILES"
$Include=@("*.log")
$cntDate = Get-Date

# First day of the current month
$firstDayMonth = Get-Date -Day 1 -Month $cntDate.Month -Year $cntDate.Year -Hour 0 -Minute 0 -Second 0

# Last day of the current month
$lastDayOfMonth = (($firstDayMonth).AddMonths(1).AddSeconds(-1))

$firstDayMonth
$lastDayOfMonth

Get-ChildItem -Path $path -recurse -include "$Include" |
 where {$_.CreationTime -ge $firstDayMonth -and
        $_.CreationTime -lt $lastDayOfMonth
        }

I tested it with another UNC path and it works! So the example you give "C:\Windows\System32\LogFiles" is accessible only to System.

Upvotes: 5

Related Questions