2

I am working in a windows environment.

I have a project that requires a short script to determine if a file with a modified date of today exists in a folder. If the file exists, it should copy it, if a file does not exist, it should return an error code.

I prefer to not use 3rd party apps. I am considering powershell.

I can pull a list to visually determine if the file exists, but I am having trouble batching to return an error if the count is zero.

Get-ChildItem -Path C:\temp\ftp\archive -Recurse | Where-Object  { $_.lastwritetime.month -eq 3 -AND $_.lastwritetime.year -eq 2013  -AND $_.lastwritetime.day -eq 21}

Any help is greatly appreciated!

4

4 回答 4

2

您可以将当前日期与每个文件 LastWriteTime 短日期的日期部分进行比较:

Get-ChildItem -Path C:\temp\ftp\archive -Recurse | Where-Object  {
   $_.LastWriteTime.ToShortDateString() -eq (Get-Date).ToShortDateString() 
}
于 2013-03-27T13:57:49.800 回答
1
Get-ChildItem $path -r | % {if((!($_.psiscontianer))-and(Get-Date $_.LastWriteTime -Uformat %D)-eq(Get-Date -UFormat %D)){$_.FullName}else{Write-Warning 'No from Today'}}

仅供参考,在进行大型工作时,例如要处理 TB 的文件,请使用 foreach-object。它比 Where-Object 更快。此方法在可用时直接处理数组中收集的对象,而不是等到所有对象都收集完毕。

总之,总有很多不同的方法可以在 PowerShell 中实现相同的结果。我提倡使用你最容易记住的东西。同时,PowerShell 可以在这些方法之间提供一些巨大的性能差异 - 了解更多信息是值得的!

您仍然可以通过计算日期使线路更有效率

$date = (Get-Date -UFormat %D)
Get-ChildItem $path -r | % {if((!($_.psiscontianer))-and(Get-Date $_.LastWriteTime -Uformat %D)-eq$date){$_.FullName}else{Write-Warning 'No from Today'}}
于 2013-03-27T20:51:23.633 回答
0

测试是否没有文件:

$out = Get-ChildItem -Path C:\temp\ftp\archive -Recurse | Where-Object  {  
   $_.LastWriteTime.ToShortDateString() -eq (Get-Date).ToShortDateString() 
};
if ($out.Count -gt 0)
//do something with your output
else
//sorry no file
于 2013-03-27T14:22:55.087 回答
0

我能够使用以下脚本:

$Date = Get-Date
$Date = $Date.adddays(-1)
$Date2Str = $Date.ToString("yyyMMdd")
$Files = gci "C:\\Temp\\FTP\\Archive"

ForEach ($File in $Files){
    $FileDate = $File.LastWriteTime
    $CTDate2Str = $FileDate.ToString("yyyyMMdd")
    if ($CTDate2Str -eq $Date2Str) {Copy-Item $File.Fullname "C:\\Temp\\FTP"; exit}
}
Throw "No file was found to process"
于 2013-03-27T14:18:24.083 回答