2013-03-27 152 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'}}