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.
Related
Unbale to compare the interger value in powershell using the -gt or -ge operator
Iam trying to get the latest number of files as a count in to a int variable. After i got the count, i need to check if it is greater than n number. But it doesn't look the value is comparing.
[int]$count_of_Files= Write-Host (Get-ChildItem $source_dir | Measure-Object).Count
if($count_of_Files -gt 3){Write-Host "True
"}
The count_of_files value is 6. But when i ran the if condition to compare the value > 3 , the output "True" not printing
Appreciate if anyone can help on this?
When creating a variable, do not use the Write-Host command ever, it will not assign it to the variable thus making it a NULL variable. Also try not to use strings for a Boolean when you can use $True or $False
[int]$count_of_Files = (Get-ChildItem $source_dir | Measure-Object).Count
IF($count_of_Files -gt 3){
$True
} Else {
$False
}
Comment Answer: Normally you should ask a new question if it is not related to your initial question, but since it is a simple adjustment of the original code, please see below.
# Get files only from $source_dir
$Files = Get-ChildItem $source_dir -File
# Created if statement to check if there are more than 3 files in the $source_dir
IF($Files.Count -gt 3){
# Assigns the top 3 files to $files_to_keep with most recent at the top
$files_to_keep = $Files | Sort-Object LastWriteTime -Descending | Select-Object -first 3
}
$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.
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"
}
}
I've written a Powershell script that would periodically delete folders on my machine.
The algorithm is as follows:
Drill down into each directory structure to the lowest subfolders
Check the creation date of the subfolder
If it's 14 days old, or older, delete it
LOG EVERYTHING (not part of the algorithm, just good practise)
When running, it operates exactly as expected...
... Except it throws the following, non-terminating exception:
Get-ChildItem : Could not find a part of the path 'C:\foo\baz'.
At C:\src\CoreDev\Trunk\Tools\BuildClean script\buildclean.ps1:55 char:15
+ Get-ChildItem <<<< -recurse -force |
+ CategoryInfo : ReadError: (C:\foo\baz:String) [Get-ChildItem],
DirectoryNotFoundException
+ FullyQualifiedErrorId : DirIOError,Microsoft.PowerShell.Commands.GetChil
dItemCommand
Why is this happening? More importantly, how can I remove it, and will it cause an issue?
The script is as follows:
# folderclean.ps1
# This script will remove each leaf node of a directory, provided that leaf is over
# 14 days old.
# CONSTANT DECLARATIONS
# testing (run on my local machine)
$proj_loc = "C:\foo", "C:\bar"
$logpath = "C:\Logs\BuildClean\$(Get-Date -format yyyyMMdd).log"
function Write-ToLogFile {
param ([string]$stringToWrite)
Add-Content $logpath -value $stringToWrite
}
# Function to check if a folder is a leaf folder.
# First, retrieve the directory $item is pointing to
# Then, create a list of children of $item that are folders
# If this list is either empty or null, return $true
# Otherwise, return $false
function Folder-IsLeaf($item) {
$ary = Get-ChildItem $item -force | ?{ $_.PSIsContainer }
if (($ary.length) -eq 0 -or $ary -eq $null) {
return $true
}
return $false
}
# Deletes leaf folders that are older than a certain threshhold.
# Get a list of children of the folder, where each child is a folder itself and
# was created over 14 days ago and the folder is a leaf
# For each of these children, delete them and increment $folderCount
# Get a list of children of the folder, where each child is a folder itself and
# was last modified over 14 days ago and the folder is a leaf
# For each of these children, delete them and increment $folderCount
function Remove-LeafFolders($path) {
$createdCount = 0
$modifiedCount = 0
Write-ToLogFile "Operation started at $(Get-Date -format "dd/MM/yyyy hh:mm:ss.fff")"
Write-ToLogFile "Looking in $proj_loc"
Write-ToLogFile ""
$start = $(Get-Date)
$proj_loc |
Get-ChildItem -recurse -force |
?{
$_.PSIsContainer -and ($_.CreationTime).AddDays(15) -lt $(Get-Date) -and $(Folder-IsLeaf $_.FullName) -eq $true
} | %{
$formattedDate = $($_.CreationTime).ToString("dd/MM/yyyy hh:mm:ss");
Write-ToLogFile "Folder $($_.FullName) is being removed; created: $formattedDate"
Remove-Item $_.FullName -recurse;
$createdCount += 1
}
$end = $(Get-Date)
$elapsed = $end - $start
Write-ToLogFile "Operation completed at $(Get-Date -format "dd/MM/yyyy hh:mm:ss.fff")."
Write-ToLogFile "Folders removed: $createdCount"
Write-ToLogFile "Time elapsed: $(($elapsed).TotalMilliseconds) ms"
Write-ToLogFile "-------------------------------"
}
Remove-LeafFolders($proj_loc)
I found this other StackOverflow question, and, after looking through the answer, I realised that the problem was the pipeline. So, I changed my code as follows:
...
$leafList = $proj_loc |
Get-ChildItem -recurse -force |
?{
$_.PSIsContainer -and ($_.CreationTime).AddDays(15) -lt $(Get-Date) -and $(Folder-IsLeaf $_.FullName) -eq $true
}
Foreach ($folder in $leafList)
{
$formattedDate = $($folder.CreationTime).ToString("dd/MM/yyyy hh:mm:ss");
Write-ToLogFile "Folder $($folder.FullName) is being removed; created: $formattedDate"
Remove-Item $folder.FullName -recurse;
$createdCount += 1
}
...
I created a few local folders and screwed around with them. No exceptions cropped up, so this appears to have worked:
Operation started at 10/12/2012 05:16:18.631
Looking in C:\foo C:\bar
Folder C:\foo\baz is being removed; created: 09/01/2010 02:00:00
Folder C:\bar\baz3\recursion is being removed; created: 01/01/2008 01:00:00
Operation completed at 10/12/2012 05:16:18.748.
Folders removed: 2
Time elapsed: 33.0033 ms
-------------------------------
Operation started at 10/12/2012 05:41:59.246
Looking in C:\foo C:\bar
Folder C:\foo\baz2\NewFolder is being removed; created: 10/10/2010 10:10:10
Folder C:\bar\baz3\barbar is being removed; created: 20/11/2012 05:37:38
Operation completed at 10/12/2012 05:41:59.279.
Folders removed: 2
Time elapsed: 21.0021 ms
-------------------------------
I think it would be easier to accomplish this sort of recursive deletion using a bottom-up approach rather than a top-down which is what Get-ChildItem gives you by default. Try this instead:
$proj_loc |
Get-ChildItem -recurse -force -Name | sort -desc | Get-Item |
? { ....
}
Currently I have a one line batch file to back up a file. I run it manually when I need to back up a file. The only thing I would like to add to it is the current date. Here is what I have:
xcopy /W /Y ACTIVE.DB ACTIVE.DB.BACKUP
the destination file should simply be ACTIVE.DB.BACKUP.YYYYMMDD. How would I go about creating a script that will allow me to double click on it from Windows Explorer and make the xcopy happen?
Just to point out that you can do this with Copy-Item e.g.:
Set-Location $path
Copy-Item ACTIVE.DB "ACTIVE.DB.$(get-date -f yyyyMMdd)" -Force -Confirm
If you're going for robust then I'd use robocopy.exe.
You can customize your filename by embedding a formatted [datetime]::now in the file name in PowerShell like so:
xcopy /W /Y ACTIVE.DB "ACTIVE.DB.BACKUP.$([datetime]::now.ToString('yyyy-MM-dd'))"
If the line feels busy and unmaintainable, you can refactor it to multiple lines:
$now = [datetime]::now.ToString('yyyy-MM-dd')
xcopy /W /Y ACTIVE.DB "ACTIVE.DB.BACKUP.$now"
To get double-click execution, I usually make a batch file that runs the PowerShell command as described here:
Set up PowerShell Script for Automatic Execution
I just made a Daily/Weekly/Monthly/Quarterly/Yearly backup script in Powershell this month, and hope it helps.
This DWMQY backup scenario is to zip a source folder to a date-named zip file, then keep the zips of:
last 7 days
4 weeks (each Friday's)
6 months (the last Friday's of each month)
4 quarters (the last month's of quarter)
2 years (the last quarter's of year).
Running as scheduled task on daily basis, it puts the zips into a target folder which is also a Microsoft OneDrive's local folder, so the zips also being remotely sync'd to OneDrive server. Those outdated (non-Friday daily or non-last-DWMQY) zips will be moved to a non-remotely-sync'd folder.
It's March 5, 2016 today, the following zips should be in the target folder:
7 days: 160304-160229-160227
4 weeks: 160304, 160226, 160219,160212
6 months: 160226, 160129, 161225, 151127, 151025, 150925
4 quarters: 151225, 150925,150626,150327
2 years: 151225, 141226
So there will be 23 zips (actually less since the dups among DWMQY), our files are 250 text documents which is 0.4 GB after zipping, so it's 23*0.4 = 9.2 GB in total, which is less than OneDrive free 15 GB quota.
For large source data, 7-zip can be used, which provides maximum 16 mil TB zip size. For directly backup folders instead of zips, haven't tried. Guessing it's a transferable procedure from the current zip way.
# Note: there are following paths:
# 1. source path: path to be backed up.
# 2. target path: current zips stored at, which is also a remote-sync pair's local path.
# 3. moved-to path: outdated zips to be moved in this non-sync'able location.
# 4. temp path: to copy the source file in to avoid zip.exe failing of compressing them if they are occupied by some other process.
# Function declaration
. C:\Source\zipSaveDated\Functions.ps1
# <1> Zip data
$sourcePath = '\\remoteMachine1\c$\SourceDocs\*'
$TempStorage = 'C:\Source\TempStorage'
$enddate = (Get-Date).tostring("yyyyMMdd")
$zipFilename = '\\remoteMachine2\d$\DailyBackupRemote\OneDrive\DailyBackupRemote_OneDrive\' + $enddate + '_CompanyDoc.zip'
Remove-Item ($TempStorage + '\*') -recurse -Force
Copy-Item $sourcePath $TempStorage -recurse -Force
Add-Type -A System.IO.Compression.FileSystem
[IO.Compression.ZipFile]::CreateFromDirectory($TempStorage, $zipFilename)
# <2> Move old files
$SourceDir = "\\remoteMachine2\d$\DailyBackupRemote\OneDrive\DailyBackupRemote_OneDrive"
$DestinationDir = "\\remoteMachine2\d$\DailyBackupRemote\bak" # to store files moved out of the working folder (OneDrive)
$KeepDays = 7
$KeepWeeks = 4
$KeepMonths = 6
$KeepQuarters = 4
$KeepYears = 2
# <2.1>: Loop files
$Directory = $DestinationDir
if (!(Test-Path $Directory))
{
New-Item $directory -type directory -Force
}
$files = get-childitem $SourceDir *.*
foreach ($file in $files)
{ # L1
# daily removal will not remove weekly copy, 7
If($file.LastWriteTime -lt (Get-Date).adddays(-$KeepDays).date `
-and $file.LastWriteTime.DayOfWeek -NotMatch "Friday" `
)
{
Move-Item $file.fullname $Directory -force
}
} # L1 >>
$files = get-childitem $SourceDir *.*
foreach ($file in $files)
{ # L1
# weekly removal will not remove monthly copy, 4
If($file.LastWriteTime -lt (Get-Date).adddays(-$KeepWeeks * 7).date `
-and (Get-LastFridayOfMonth ($file.LastWriteTime)).Date.ToString("yyyyMMdd") -NotMatch $file.LastWriteTime.Date.ToString("yyyyMMdd")
)
{
Move-Item $file.fullname $Directory -force
}
} # L1 >>
$files = get-childitem $SourceDir *.*
foreach ($file in $files)
{ # L1
# monthly removal will not remove quarterly copy, 6
If($file.LastWriteTime.Month -lt ((Get-Date).Year - $file.LastWriteTime.Year) * 12 + (Get-Date).Month - $KeepMonths `
-and $file.LastWriteTime.Month -NotIn 3, 6, 9, 12
)
{
Move-Item $file.fullname $Directory -force
}
} # L1 >>
$files = get-childitem $SourceDir *.*
foreach ($file in $files)
{ # L1
# quarterly removal will not remove yearly copy, 4
If($file.LastWriteTime.Month -lt ( (Get-Date).Year - $file.LastWriteTime.Year) * 12 + (Get-Date).Month - $KeepQuarters * 3 `
-and $file.LastWriteTime.Month -NotIn 12
)
{
Move-Item $file.fullname $Directory -force
}
} # L1 >>
$files = get-childitem $SourceDir *.*
foreach ($file in $files)
{ # L1
# yearly removal will just go straight ahead. 2
If($file.LastWriteTime.Year -lt (Get-Date).Year - $KeepYears )
{
Move-Item $file.fullname $Directory -force
}
} # L1 >>
<Functions.ps1>
function Get-TimesResult3
{
Param ([int]$a,[int]$b)
$c = $a * $b
Write-Output $c
}
function Get-Weekday {
param(
$Month = $(Get-Date -format 'MM'),
$Year = $(Get-Date -format 'yyyy'),
$Days = 1..5
)
$MaxDays = [System.DateTime]::DaysInMonth($Year, $Month)
1..$MaxDays | ForEach-Object {
Get-Date -day $_ -Month $Month -Year $Year |
Where-Object { $Days -contains $_.DayOfWeek }
}
}
function Get-LastFridayOfMonth([DateTime] $d) {
$lastDay = new-object DateTime($d.Year, $d.Month, [DateTime]::DaysInMonth($d.Year, $d.Month))
$diff = ([int] [DayOfWeek]::Friday) - ([int] $lastDay.DayOfWeek)
if ($diff -ge 0) {
return $lastDay.AddDays(- (7-$diff))
}
else {
return $lastDay.AddDays($diff)
}
}