Reputation: 3
We have a daily job which dumps .txt files from vendors and I am writing a powershell script to process the file based on file create date. For instance when the script is run on 02/10/20 it will check if the .txt files were created on 02/09/20 if not raise a flag.
$file = "C:\vendor\sale\vendor_a_02092020.txt"
if($file.CreationTime.Date -e [datetime]::Today.AddDays(-1))
{
Write-Output "The file in the path $file created on $file.CreationTime is the latest file"
}
else
{
Write-Output "The file in the path $file created on $file.CreationTime is not the latest file"
}
I am trying to print the file path and file created date in Write-Output. Currently it does not print the full file path or the file create date.
Upvotes: 0
Views: 795
Reputation: 24071
Another a way to print complex strings is to use composite formatting. The idea is to add indexed placeholders for variables and a list of values.
If there are several variables with long names, composite formatting greatly simplifies string building. Like so,
Write-output ("The file in the path {0} created on {1} is not the latest file" -f `
$f.FullName, $f.CreationTime)
Parenthesis are required so that a formatted string is passed to write-output
.
As a side note, Powershell's got Get-Date
which is more idiomatic. The functionality is equal, but I prefer Powershell-ish version over .Net style. Not that there is any difference but how the code looks.
# Idiomatic psh
$file.CreationTime.Date -eq (Get-Date).AddDays(-1).Date
# .Net -styled
$file.CreationTime.Date -eq [datetime]::Today.AddDays(-1).Date
Upvotes: 0
Reputation: 11364
You can use Get-Item
to get the file information (including full path).
Also, if you are printing a variable with its property inside a string, you have to use $($variable.property)
to keep the property part of the variable (instead of string).
Comparisons are done with -eq ... not sure if that was misspelled when you copied it to SO. -le (less than or equal), -ge (greater than or equal) etc.
If you are comparing Date of the DateTime, make sure you select Date on both sides of the equation as well.
$file = Get-Item "C:\vendor\sale\vendor_a_02092020.txt"
if($file.CreationTime.Date -eq [datetime]::Today.AddDays(-1).Date)
{
Write-Output "The file in the path $(file.FullName) created on $($file.CreationTime) is the latest file"
}
else
{
Write-Output "The file in the path $(file.FullName) created on $($file.CreationTime) is not the latest file"
}
Upvotes: 1