首页 > 解决方案 > 如何检查文件创建日期并在写入输出中打印

问题描述

我们有一项日常工作,它从供应商那里转储 .txt 文件,我正在编写一个 powershell 脚本来根据文件创建日期处理文件。例如,当脚本在 2020 年 2 月 10 日运行时,它将检查 .txt 文件是否是在 2020 年 2 月 9 日创建的,如果没有引发标志。

$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"
    }

我正在尝试在 Write-Output 中打印文件路径和文件创建日期。目前它不打印完整的文件路径或文件创建日期。

标签: powershell

解决方案


  • 可以Get-Item用来获取文件信息(包括完整路径)。

  • 此外,如果要在字符串中打印其属性的变量,则必须使用$($variable.property)来保留变量的属性部分(而不是字符串)。

  • 比较是用 -eq 完成的......不确定当你将它复制到 SO 时是否拼写错误。-le(小于或等于),-ge(大于或等于)等。

  • 如果要比较 DateTime 的 Date,请确保在等式两边也选择 Date。

$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"
}

推荐阅读