$timeLimit1 = Get-Date.AddDays(-90)
Get-ChildItem <path> | ? {$_.LastWriteTime -le $timeLimit1 } | Remove-Item
So I have the easier part, but I am trying to figure out how to do something a little more complex.
I am setting up a backup deletion routine. The requirement is to keep the last 90 days of backups, then the final day of each month prior to that for the current year and finally a backup from December 31st for the prior 2 years.
I couldn't find any examples other than just a single check; is it possible to do several checks to automate that.
I suggest writing a custom filter to apply the logic e.g.
filter MyCustomFilter{
$File = $_
$FileDate = $File.LastWriteTime
$Now = (Get-Date)
$FileAgeDays = ($Now - $FileDate).TotalDays
if (
# Keep files for at least 90 days
( $FileAgeDays -lt 91
) -or
# Keep files from last day of the month this year
( $FileDate.Year -eq $Now.Year -and
$FileDate.Month -ne $FileDate.AddDays(1).Month
) -or
# Keep files from 31 Dec for up to 2 years
( $FileAgeDays -lt ( 2 * 365 ) -and
$FileDate.Month -eq 12 -and
$FileDate.Day -eq 31
)
) {
# File should be kept, so nothing is returned by the filter
} else {
# File should be deleted, so pass the file down the pipeline
write-output $File
}
}
Now your overall code would look something like this:
get-childItem -path <path> |
where-object { -not $_.PSIsContainer } |
MyCustomFilter |
Remove-Item
It goes without saying, that proper testing is required before letting this loose on production systems.
EDIT: A Simpler test for last day of month
I thought of a neater 'last day of the month' test, which is simply to compare the month property of the date under test, with the month property of the following day e.g.
$FileDate.Month -ne $FileDate.AddDays(1).Month
will return $true if $FileDate is last day of the month.
Just create an array of your "special" dates and add them to your filter.
$timeLimit1 = Get-Date
$timeLimit1.AddDays(-90)
$specialDates = (Get-Date "31-12-2014"), (Get-Date "31-05-2017") # continue the list
Get-ChildItem <path> | ? {$_.LastWriteTime -le $timeLimit1 -and $specialDates -notcontains $_.LastAccessTime.Date } | Remove-Item
I would also make a function to find the "special" dates.
Related
I have a backup script that puts files in a dated directory every night. I have another script, below, that goes through a list of dated directories and if it's within the range I want to delete, I will delete the directory, keeping the Saturday dated file. For some reason, for the dir dated Saturday, 1/12/2019, it's being deleted, even though the if statement should indicate it wouldn't be deleted.
This is my code:
function WeeklyCleanup($folderWeeklyCleanupDatedSubdirs) {
#find out date range to cleanup
$lastSaturday = GetLastSaturdayDate
$lastSaturday = [datetime]$lastSaturday
$weekAgoSunday = GetWeekAgoSundayDate
$weekAgoSunday = [datetime]$weekAgoSunday
#find out filename with Saturday date before current date but within week
Get-ChildItem $folderWeeklyCleanupDatedSubdirs | ForEach-Object {
write-output $_
#check to see if item is before day we want to remove
$temp = $_
$regex = [regex]::Matches($temp,'([0-9]+)-([0-9]+)-([0-9]+)')
if($regex.length -gt 0) #it matched
{
$year = $regex[0].Groups[1].Value
$month = $regex[0].Groups[2].Value
$day = $regex[0].Groups[3].Value
write-output $year
write-output $month
write-output $day
write-output "*************"
$dirDate = $regex[0].Groups[0].Value + " 12:00:00 PM"
write-output $dirDate
if($dirDate.length -gt 0) #it matched
{
$dateTimeObjectFromRegex = [datetime]$dirDate
##########this next statement is letting $dateTimeObjectFromRegex of 1/12/2019 through when it shouldn't. See time comparison below
if(([datetime]$dateTimeObjectFromRegex -lt [datetime]$lastSaturday) -and ([datetime]$dateTimeObjectFromRegex -ge [datetime]$weekAgoSunday)) #we're removing extra ones over last week, keep Saturday
{
$dirPathToRemove = Join-Path -path $folderWeeklyCleanupDatedSubdirs -ChildPath $temp.ToString()
Get-ChildItem -Path $dirPathToRemove #list the dir
#remove dir
if(-Not (Test-Path $dirPathToRemove )) #-PathType Container
{
$global:ErrorStrings.Add("Exception: No such path, $dirPathToRemove;; ")
write-output "++ Error: An error occured during copy operation. No such path, $dirPathToList ++"
}
else
{
#remove dir and subdirs
Remove-Item $dirPathToRemove -Force -Recurse
Get-ChildItem -Path $dirPathToRemove #list the dir
}
#Write-Output $_
#Write-Output " 1 "
} #if within last week
} #if dirDate length
} #if regex matched
} #get-childItem
}
function GetLastSaturdayDate()
{
$date = Get-Date #"$((Get-Date).ToString('yyyy-MM-dd'))"
#for($i=1; $i -le 7; $i++){
# if($date.AddDays(-$i).DayOfWeek -eq 'Saturday') #if found Saturday
# {
# $date.AddDays(-$i)
# $newDate = $date.AddDays(-$i)
# break
# }
#}
$newdate = $date.AddDays(-($date.DayOfWeek+1)%7)
return $newdate
}
function GetWeekAgoSundayDate()
{
$numberOfWeeks = 1; #week ago
$date = Get-Date #"$((Get-Date).ToString('yyyy-MM-dd'))"
#for($i=1; $i -le 7; $i++){
# if(($date.AddDays(-$i).DayOfWeek -eq 'Sunday') -and ($date.AddDays(-$i) -ne $date)) #if found a Sunday and it's not today
# {
# $date.AddDays(-$i)
# $newDate = $date.AddDays(-$i)
# break
# }
#}
#$newdate = $date.AddDays(-($date.DayOfWeek+1)%0)
$numDaysSincePreviousDate = $date.DayOfWeek.value__ + 0 #0 is Sunday
([System.DateTime] $previousDayOfWeek = $date.AddDays(- $numDaysSincePreviousDate)) | Out-Null
$previousDate = $previousDayOfWeek.AddDays(-($numberOfWeeks *7)).ToString("MM-dd-yyyy")
return $previousDate
}
The WeeklyCleanup script is called with this parameter:
$folderToCleanupDatedSubdirs = [System.IO.DirectoryInfo]"E:\Bak_TestDatedFolderCleanup"
For time comparison:
Directory item toLocRobo_2019-01-12 - Once I get regex with timestamp, I add the time in of 12:00:00 PM for the $dirDate variable. This becomes $dateTimeObjectFromRegex. Debugger shows it as Saturday, January 12, 2019 12:00:00 PM
When I run the program, I get $lastSaturday as Saturday, January 12, 2019 3:59:04 PM
When I run the program, debugger also shows $weekAgoSunday as Sunday, January 6, 2019 12:00:00 AM
From what I can see, it shouldn't be getting through that if statement to delete the dir for 1/12/2019.
I tried casting the dates to datetime to make sure it wasn't doing a string comparison in the if statement, even though I casted it above.
I've been looking at these links for more info on this, but it looks correct to me:
dateTimeComparisons not working expectedly
convert string to datetime
All I can think is that it's still treating the datetime in the first part of the if statement comparison like a string, so it's thinking 3:59 PM is greater than 12:00 PM. Any ideas how to get this date check to work? I don't care about times, just want to make sure it doesn't get rid of the Saturday-dated file from this past week, but only cleanup other dir's over that week.
Update
Made changes suggested by #brianist below, and it worked great. This is what it looks like so far. Saturday and Sunday functions haven't changed. He's asking me to post it. If he has any other suggestions how to get it to treat/compare what's returned from the last Saturday and weekAgoSunday functions as dates, without the cast, that'd make it look less clunky/easier to read. Thanks Brian!
#do weekly cleanup of DisasterBackup folder
function WeeklyCleanup($folderWeeklyCleanupDatedSubdirs) {
#find out current date
$currentDate = "$((Get-Date).ToString('yyyy-MM-dd'))" #example 2019-01-15
$currentDayOfWeek = (get-date).DayOfWeek.value__ #returns int value for day of week
#find out current day of week
$lastSaturday = GetLastSaturdayDate
$lastSaturday = [datetime]$lastSaturday #if we take away extra casts it won't do comparison line (-lt and -ge)
$weekAgoSunday = GetWeekAgoSundayDate
$weekAgoSunday = [datetime]$weekAgoSunday #if we take away extra casts it won't do comparison line (-lt and -ge), and can't move cast before function call because it isn't recognizing function anymore if I do
#find out filename with Saturday date before current date but within week
#get each dir item to check if we need to remove it
Get-ChildItem $folderWeeklyCleanupDatedSubdirs | ForEach-Object {
write-output $_
#check to see if item is before day we want to remove
$temp = $_
if($_.Name -match '(\d{4}-\d{2}-\d{2})$'){ #regex
write-output $Matches[1]
$dirDate = Get-Date $Matches[1] #turn regex into date
if(([datetime]$dirDate.Date -lt [datetime]$lastSaturday.Date) -and ([datetime]$dirDate.Date -ge [datetime]$weekAgoSunday.Date)) #we're removing extra ones over last week, keep Saturday
{
$dirPathToRemove = Join-Path -path $folderWeeklyCleanupDatedSubdirs -ChildPath $temp.ToString()
Get-ChildItem -Path $dirPathToRemove #list the dir
#remove dir
if(-Not (Test-Path $dirPathToRemove )) #-PathType Container
{
$global:ErrorStrings.Add("Exception: No such path, $dirPathToRemove;; ")
write-output "++ Error: An error occured during copy operation. No such path, $dirPathToList ++"
}
else
{
#remove dir and subdirs
Remove-Item $dirPathToRemove -Force -Recurse
Get-ChildItem -Path $dirPathToRemove #list the dir
}
} #if within last week
} #if regex matched
} #get-childItem
}
Re-reading your last sentence, I now see that your intention is to ignore times, not to include them in your comparison.
You are right to want to use [DateTime] objects when comparing, but do note that those objects always include a time.
Conveniently you can use the .Date property of such an object which returns a new one, with the time set to midnight. This is useful for comparing because the time would no longer be a factor.
Pulling out my modified if statement from below, you can do it like this:
if ($dirDate.Date -lt $lastSaturday.Date -and $dirDate.Date -ge $weekAgoSunday.Date) {
# do stuff
}
Now you're only comparing dates, and ignoring time!
Based on what you're showing it looks like the if statement is working as expected. To summarize, you say that:
$dateTimeObjectFromRegex is Saturday, January 12, 2019 12:00:00 PM
$lastSaturday is Saturday, January 12, 2019 3:59:04 PM
$weekAgoSunday is Sunday, January 6, 2019 12:00:00 AM
The conditional is:
if(([datetime]$dateTimeObjectFromRegex -lt [datetime]$lastSaturday)
-and ([datetime]$dateTimeObjectFromRegex -ge [datetime]$weekAgoSunday))
Therefore in pseudo-code it's:
if (
("January 12, 2019 12:00:00 PM" is earlier than "January 12, 2019 3:59:04 PM") # true
and
("January 12, 2019 12:00:00 PM" is later or the same as "January 6, 2019 12:00:00 AM") # true
) # true
I do want to point out that you are doing an awful lot of unnecessary datetime chopping and casting, and cleaning that up would help with readability and with debugging these types of issues.
$lastSaturday = GetLastSaturdayDate
$lastSaturday = [datetime]$lastSaturday
$weekAgoSunday = GetWeekAgoSundayDate
$weekAgoSunday = [datetime]$weekAgoSunday
Your functions already return [DateTime] objects, so there's no need for those casts.
$temp = $_
$regex = [regex]::Matches($temp,'([0-9]+)-([0-9]+)-([0-9]+)')
if($regex.length -gt 0) #it matched
{
$year = $regex[0].Groups[1].Value
$month = $regex[0].Groups[2].Value
$day = $regex[0].Groups[3].Value
write-output $year
write-output $month
write-output $day
write-output "*************"
$dirDate = $regex[0].Groups[0].Value + " 12:00:00 PM"
write-output $dirDate
This is quite complex, you could simplify it down to something like this:
if ($_.Name -match '(\d{4}-\d{2}-\d{2})$') {
# in here, you know the match was successful
$dirDate = Get-Date $Matches[1] # double check this, might need .Groups or something
if ($dirDate -lt $lastSaturday -and $dirDate -ge $weekAgoSunday) {
# do stuff
}
}
Probably some more optimizations etc. Hope this was helpful!
i have to make powershell file where i need to compare 2 dates and delete folder which is like more than 10 days of last write item . like today is 30 October i need to delete folder where comparision of dates give 11 12 and 13 days
#ChildItem "\\server\Backup" -Recurse | Where-Object {$_.LastWriteTime -gt (Get-Date).AddDays.(-30) }
#$fulllist =Get-ChildItem "\\server\Backup\SharePoint Backup\"| Where-Object {$_.LastWriteTime -gt (Get-Date).AddDays.(5) }
$fulllist =Get-ChildItem "\\server\Backup\SharePoint Backup\"
#$fulllist =Get-ChildItem "\\server\Backup\SharePoint Backup\" -Recurse | Where-Object {$_.LastWriteTime -gt (Get-Date).AddDays.(-20) }
foreach ($fileitem in $fulllist)
{
$filename_big = $fileitem.FullName
#write-host $filename_big
$d = [datetime](Get-ItemProperty -Path $filename_big -Name LastWriteTime).lastwritetime
$d1=(get-date)
#write-host $d
#write-host $d1
$ts = New-TimeSpan -Start $d -End $d1
$ts.Days # Check results\
write-host $ts
if($ts -gt 10)
{
write-host "inside"
}
# Move-Item -Path $filename_big -Destination "\\DBORION\d$\backup"
}
iam comparing two dates $d & d1 and days are greater than 10 that folders should get deleted.
but with output iam getting its going inside for all folders whether its 10 days or 5 days ,please find output
0
00:58:29.2923431
inside
0
13:33:32.4388907
inside
0
07:02:28.0900378
inside
0
03:52:35.3425970
inside
0
00:58:29.4017400
inside
13
13.08:49:05.4930775
inside
12
12.08:49:06.3403154
inside
11
11.08:48:31.4681438
inside
10
10.08:48:18.6859604
inside
9
9.08:49:01.2220544
inside
8
8.08:39:56.7230423
inside
7
7.08:48:15.3242000
inside
6
6.08:49:03.6123002
inside
5
5.08:49:08.5439345
inside
4
4.08:49:06.6188386
inside
3
3.08:49:07.2066345
inside
2
2.08:49:06.2290185
inside
1
1.08:45:07.0454477
inside
0
08:47:24.1939025
inside
ok so i got this
$fulllist = Get-ChildItem "\\Server\Backup\SharePoint Backup\"
$Days = 12
foreach ($fileitem in $fulllist)
{
$filename_big = $fileitem.FullName
$deletedate = (Get-Date).AddDays(-$Days)
$Folderdate = [datetime](Get-ItemProperty -Path $filename_big -Name LastWriteTime).lastwritetime
if($Folderdate -le $deletedate)
{
$filename_big
Remove-Item -Path $filename_big -Force -Confirm:$false
}
}
now my only concern is its asking for confirmation of deletion, i dont want that popup box how to bypass that
I think the problem is that your variable $ts is a timespan. A timespan can never be greater then 10, because it is a number. In your if clause you should use:
if($ts.Days -gt 10)
And some other maybe needfull advices to spare some byte:
when you define your $d variable, this can be done much shorter: $d = $fileitem.lastwritetime - the $fileitem variable itself has the lastwritetime property.
when assigning a function to a variable, there is no need for round brackets: just use $d1 = Get-Date. The brackets are only needed if you want to assign a propery of the function, for example $d = (Get-Date).DayOfWeek.
you could avoid creating the timespan by this: if($d -gt $d1.addDays(-10)). This compares your file timestamp $d with the current time minus 10 days, meaning the point in time exactly 10 days ago.
And to bypass confirmation when you delete files: use the -force parameter.
I've got a script that's causing me grief, where the where clause in the final pip isn't filtering dates out by the criteria I want.
The script is taking a CSV as an input, and the script parses the dates it finds so that they are in the correct date format.
The dates are then processed in a Where-Object clause to select all dates that are from within the past month onwards (all records with dates prior are not included). The problem I'm having is that this filter isn't working, and I'm getting all records included regardless.
My question is, what is wrong with my script and how can I fix this where clause.
Here's the code that correlates directly to the above:
if ($o.'Joined Company') {
$StartDate = [datetime]::ParseExact($o.'Joined Company','d/MM /yyyy',$null).ToString("dd/M/yyyy")
$o.StartDateObj = $StartDate
} elseif ($o.'Joined Company' -eq '') {
$o.StartDateObj = $null
}
if ($o.'last day of duty') {
$EndDate = [datetime]::ParseExact($o.'Last Day of Duty','d/MM/yyyy',$null).ToString("dd/M/yyyy")
$o.EndDateObj = $EndDate
} elseif ($o.'Last Day of Duty' -eq '') {
$o.EndDateObj = $null
}
Write-Debug ("" + $o.EndDateObj)
Write-Debug ("" + $o.StartDateObj)
}
$Today = Get-Date
$LastMonth = $Today.AddMonths(-1)
$obj | Where-Object {$_.Company -like "New Zealand"} |
Where-Object {($_.EndDateobj -gt $LastMonth) -or ($_.EndDateobj -eq $null)} |
It's just a snippit of the full script, which can be found here.
I am very new to PowerShell, and I was hoping I could get some help creating a script that tells me the modified date of a file.
I wish I knew more about PowerShell, as I feel like I am asking a lot (all my free-time this week will be dedicated to learning PowerShell better). Pointing me in the direction of where to learn how to do this would be very helpful as well.
Here is the complete rundown. I need to run a report daily that checks a list of computers at 90 different stores to make sure their a certain backup was performed. The modified date should tell if the backup had been performed, and will be set to the previous date.
If the modified date is yesterday, then there does not need to be an output. If it is not yesterday, I would like to have the output in the PowerShell window, or to a text file, whichever would be easier.
I also have to check that a folder is no older than seven days for each of the 90 stores, with the same criteria for the output. The idea that I have would be like this for each store
For Store 1:
Check file date for \\server\store\computer\c:\folder\"newest modified date in folder"
if date equals yesterday
then do nothing
if date does not equal yesterday
then output "Test did not backup"
check folder modified date for \\server\sample\store\backupfolder
if date equals <7 days old
then do nothign
if date equals >7 days old
then output "test did not backup"
Sorry for not proving my research effort, I am very new to Powershell and I was on a deadline to get this done. I have, since yesterday, learned how to do everything that I needed to do with this script. Thanks to #Keith for setting me on the correct path. I ended up using the following code to accomplish my goal of only out-putting the location where result was false.
$a = Get-ChildItem \\server\XXX\Received_Orders\*.* | Where{$_.LastWriteTime -ge (Get-Date).AddDays(-7)}
if ($a = (Get-ChildItem \\server\XXX\Received_Orders\*.* | Where{$_.LastWriteTime -ge (Get-Date).AddDays(-7)}))
{
}
Else
{
'STORE XXX HAS NOT RECEIVED ANY ORDERS IN THE PAST 7 DAYS'
}
$b = Get-ChildItem \\COMP NAME\Folder\*.* | Where{$_.LastWriteTime -ge (Get-Date).AddDays(-1)}
if ($b = (Get-ChildItem \\COMP NAME\TFolder\*.* | Where{$_.LastWriteTime -ge (Get-Date).AddDays(-1)}))
{
}
Else
{
'STORE XXX DID NOT RUN ITS BACKUP LAST NIGHT'
}
If you run the Get-Item or Get-ChildItem commands these will output System.IO.FileInfo and System.IO.DirectoryInfo objects that contain this information e.g.:
Get-Item c:\folder | Format-List
Or you can access the property directly like so:
Get-Item c:\folder | Foreach {$_.LastWriteTime}
To start to filter folders & files based on last write time you can do this:
Get-ChildItem c:\folder | Where{$_.LastWriteTime -gt (Get-Date).AddDays(-7)}
To get the modified date on a single file try:
$lastModifiedDate = (Get-Item "C:\foo.tmp").LastWriteTime
To compare with another:
$dateA= $lastModifiedDate
$dateB= (Get-Item "C:\other.tmp").LastWriteTime
if ($dateA -ge $dateB) {
Write-Host("C:\foo.tmp was modified at the same time or after C:\other.tmp")
} else {
Write-Host("C:\foo.tmp was modified before C:\other.tmp")
}
Here's what worked for me:
$a = Get-ChildItem \\server\XXX\Received_Orders\*.* | Where{$_.LastWriteTime -ge (Get-Date).AddDays(-7)}
if ($a = (Get-ChildItem \\server\XXX\Received_Orders\*.* | Where{$_.LastWriteTime -gt (Get-Date).AddDays(-7)}
#Im using the -gt switch instead of -ge
{}
Else
{
'STORE XXX HAS NOT RECEIVED ANY ORDERS IN THE PAST 7 DAYS'
}
$b = Get-ChildItem \\COMP NAME\Folder\*.* | Where{$_.LastWriteTime -ge (Get-Date).AddDays(-1)}
if ($b = (Get-ChildItem \\COMP NAME\TFolder\*.* | Where{$_.LastWriteTime -gt (Get-Date).AddDays(-1)))}
{}
Else
{
'STORE XXX DID NOT RUN ITS BACKUP LAST NIGHT'
}
You can try dirTimesJS.bat and fileTimesJS.bat
example:
C:\>dirTimesJS.bat %windir%
directory timestamps for C:\Windows :
Modified : 2020-11-22 22:12:55
Modified - milliseconds passed : 1604607175000
Modified day of the week : 4
Created : 2019-12-11 11:03:44
Created - milliseconds passed : 1575709424000
Created day of the week : 6
Accessed : 2020-11-16 16:39:22
Accessed - milliseconds passed : 1605019162000
Accessed day of the week : 2
C:\>fileTimesJS.bat %windir%\notepad.exe
file timestamps for C:\Windows\notepad.exe :
Modified : 2020-09-08 08:33:31
Modified - milliseconds passed : 1599629611000
Modified day of the week : 3
Created : 2020-09-08 08:33:31
Created - milliseconds passed : 1599629611000
Created day of the week : 3
Accessed : 2020-11-23 23:59:22
Accessed - milliseconds passed : 1604613562000
Accessed day of the week : 4
PowerShell code to find all document library files modified from last 2 days.
$web = Get-SPWeb -Identity http://siteName:9090/
$list = $web.GetList("http://siteName:9090/Style Library/")
$folderquery = New-Object Microsoft.SharePoint.SPQuery
$foldercamlQuery =
'<Where> <Eq>
<FieldRef Name="ContentType" /> <Value Type="text">Folder</Value>
</Eq> </Where>'
$folderquery.Query = $foldercamlQuery
$folders = $list.GetItems($folderquery)
foreach($folderItem in $folders)
{
$folder = $folderItem.Folder
if($folder.ItemCount -gt 0){
Write-Host " find Item count " $folder.ItemCount
$oldest = $null
$files = $folder.Files
$date = (Get-Date).AddDays(-2).ToString(“MM/dd/yyyy”)
foreach ($file in $files){
if($file.Item["Modified"]-Ge $date)
{
Write-Host "Last 2 days modified folder name:" $folder " File Name: " $file.Item["Name"] " Date of midified: " $file.Item["Modified"]
}
}
}
else
{
Write-Warning "$folder['Name'] is empty"
}
}
Whats the powershell command for finding files in a folder that do not meet a criteria of date range for the Get-Childitem filter of LastWriteTime.
So, check to see if a directory has files that DO NOT contain any files that have LastWriteTime between 01/10/2012 (1st Oct) to 25/10/2012 (25th Oct).
I want to display the folders that DO NOT have any files that are in that range...that way I know they are old and the whole directory can be deleted.
example of this is:
Folder1 - some files written within October - ignore this whole folder and do not display these in the results
Folder2 - NO file has LastWriteTime written in the month of October and so this folder and files should be displayed.
I know this can be done with Get-ChildItem and I am stuck on the bit below..
Get-ChildItem E:\LogArchive -Recurse | Where-Object{$_.LastWriteTime.......?
Simple solution off top of the head is this:
Where-Object{ $_.LastWriteTime -lt $startDate -or $_.LastWriteTime -gt $endDate }
where $startDate is 01/10/2012 (1st Oct) and $endDate is 25/10/2012 (25th Oct).
Problem with this approach is that it does not account for time factor in the [datetime]. So in your example, if you have 25-Oct-2012 as an upper bound, it will return files created at 25-Oct-2012 9:00, which you may not want.
Below code calculates [datetime]'s with time part truncated, based on the input [datetime], and builds the month-to-date date range of ($dayStart, $dayEnd):
$entry_date = "20-Oct-2012 9:00" #to feed current date, use this: Get-Date
$dayEnd = Get-Date $entry_date -Minute 0 -Hour 0 -Second -0;
$dayStart = Get-Date $endDate -Day 1;
$dayStart, $dayEnd
For this sample code, here is the output:
Monday, October 01, 2012 12:00:00 AM
Saturday, October 20, 2012 12:00:00 AM
Notice this approach is flexible, because you can set $entry_date to either Date or String, and it may or may not have time part - it will work in all those cases. You can then have this code in Where-Object:
Where-Object{ $_.LastWriteTime -lt $dayStart -or $_.LastWriteTime -ge $dayEnd.AddDays(1) }
Notice how -ge $dayEnd.AddDays(1) fixes the issue when comparing 25-Oct-2012 to 25-Oct-2012 9:00.
Try this:
[datetime]$startDate = "10/01/2012" # or $startDate = get-date -Date 1/10/2012
[datetime]$endDate = "10/25/2012" # or $endDate = get-date -Date 25/10/2012
? { $_.LastWriteTime -lt $startDate -or $_.LastWriteTime -gt $endDate }