2013-03-27 170 views
2

我在一个Windows环境中工作。Powershell和最后修改日期

我有一个项目,需要一个简短的脚本来确定文件夹中是否存在修改日期的文件。如果文件存在,它应该复制它,如果文件不存在,它应该返回一个错误代码。

我更喜欢不使用第三方应用程序。我正在考虑PowerShell。

我可以拉出一个列表来直观地确定文件是否存在,但是如果计数为零,我无法批量返回错误。

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

任何帮助非常感谢!

回答

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" 
+0

您也可以使用复制项目作为一个变量来捕获错误状态(真假)。 $ copyStatus = {Copy-Item $ File.Fullname“C:\\ Temp \\ FTP”} – 2013-03-27 14:29:19

1

您可以比较反对的日期部分只有每个文件的当前日期LastWriteTime短日期:

Get-ChildItem -Path C:\temp\ftp\archive -Recurse | Where-Object { 
    $_.LastWriteTime.ToShortDateString() -eq (Get-Date).ToShortDateString() 
} 
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 
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'}} 

F.Y.I.当做大型工作时,比如如果你要经历TB的文件,使用foreach对象。它比Where-Object快。此方法在可用时直接处理数组中收集的对象,并且不会等到收集所有对象。

In summary, there always a lot of different ways to achieve the same result in PowerShell. I advocate using what is easiest for you to remember. At the same time, PowerShell can provide some big performance differences between the approaches – and it pays to know more!

您仍然可以行多一点效率,通过计算日期

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