2016-11-15 106 views
0

目標是刪除x天以前的文件。用於複製測試。 發現了多個關於如何做到這一點的文章 - 但是我遇到的問題是,無論變量使用的屬性和比較所有文件都被移動(複製)。其次,嘗試將結果傳遞給日誌文件將創建該文件,但不會寫入該文件。我錯過了一些東西但看不到它。關於我做錯了什麼輸入是讚賞!Powershell刪除x天前的文件

$SDirectory = "C:\TestOne*" 
$Destpath = "C:\TestTwo" 
$limit = (Get-Date).Date.AddDays(-2) 
$Full = Get-childitem -path $SDirectory -Recurse -Include *.bak,*.trn 

foreach ($i in $Full) 
{ 
    ##if ($i.CreationTime -gt ($(Get-Date).adddays(-2))) 
    if ($i.LastWriteTimeUtc -gt $limit) 
    { 
     Copy-Item -Path $Full -Destination $Destpath -Force | Out-File C:\Admin\Results11.txt -Append 
    } 
} 
+0

您正在使用$ Full而不是$ i.Fullname在副本中,並且您期望從副本得到什麼結果? – LotPings

+0

複製當然,直到現在我還沒有看到它告訴它複製一切。 – GlennUrquhart

+0

但除了做它的作業副本沒有輸出,你可以追加到任何地方,只要你省略-passthru選項,那就像dir一樣醜陋。 – LotPings

回答

1

所有文件被複制的原因是因爲你實際複製:

Copy-Item -Path $Full ... 

我想你想要更多的東西是這樣的:

Copy-Item -Path $($i.FullName) ... 

捕獲輸出使用-PassThru

Copy-Item -Path $($i.FullName) -Destination $Destpath -PassThru -Force | Out-File C:\Admin\Results11.txt -Append 
+0

時工作你也想確保使用-lt而不是-gt,如果你試圖複製文件比x天更早比x天更新 –

+0

非常感謝!現在我看到我做錯了,假設for-每個人都會處理它。 – GlennUrquhart

+0

我不知道-passthru真的pratics,ty – Esperento57

0

這就是我想出的:

$SDirectory = "C:\TestOne*" 
$Destpath = "C:\TestTwo" 
$limit = (Get-Date).Date.AddDays(-2) 
$files = Get-ChildItem -Path "$SDirectory" | % { 
    if ($_.CreationTime -gt $limit) { 
    Copy-Item -Path $_.FullName "$Destpath" 
    Add-Content "C:\Admin\Results11.txt" -Value $_.Name 
    } 
} 
+0

是的,正如Mike Garuccio所說,根據你需要的結果你可以使用-lt或-gt。 –

相關問題