I am trying to output $message in case a file or multiple files in a folder match today's or yesterday's date. In this case, if the file matches the dates, it should output a message for each file, for example, "file $filename matches", where $filename is the name of the file that matched the date.
On the other hand if a file doesn't match the current date or yesterday's date it will also return a message, but only one message with the filenames which doesn't match the date.
That is not happening with the following code:
$in = $false
foreach ($file in Get-ChildItem -Path $Directory) {
$today = $file.LastWriteTime.Date -eq [datetime]::Today
$yesterday = $file.LastWriteTime.Date -eq [datetime]::Today.AddDays(-1)
if ($today -or $yesterday) {
$message = "file exists"
$in = $true
Write-Output $message
}
}
if ($in -eq $false) {
$message_error = "file does not exist"
Write-Output $message_error
}
Instead when a file matches the dates (yesterday's or today's date) it outputs the message multiple times, more than 20x if indented like above.
As for if it doesn't match, it is outputting only 1x but it should be 2x because there are 2 files that don't match the dates.
Can anyone give me an hint?
Output should look like
If file or files in folder matches date:
"File example.txt matches date
and
File example2.txt matches date"
Else if files in folder don't match date:
"File example.txt, example2.txt don't match dates"
EDIT
Instead I am trying like this:
$in = $false
foreach ($file in Get-ChildItem -Path $Directory) {
$today = $file.LastWriteTime.Date -eq [datetime]::Today
$yesterday = $file.LastWriteTime.Date -eq [datetime]::Today.AddDays(-1)
if ($today -or $yesterday) {
$msg_found = "file" + $file "exists"
$in = $true
} else {
$msg_notfound = "File" + $file + "Not found"
}
Write-Output $msg_notfound
Write-Output $msg_found
Here the messages are outputted in the right amount but they appear both in any circunstance. Would it solve if I use an if loop?