2013-08-28 76 views
0

嘿傢伙,所以我寫了這個腳本來自動刪除指定文件夾中的文件。使用powershell刪除舊文件

$oldTime = [int]25 # 0 days 
$old2Time = [int] 10 
foreach ($path in "C:\Test") { 
Write-Host "Trying to delete files older than days, in the folder $path" -  
ForegroundColor Green 
# Write information of what it is about to do 
Get-ChildItem $path -Recurse -Include "*.txt", "*.docx", "*.xlsx" #| WHERE  
{($_.CreationTime -le $(Get-Date).AddDays($oldTime))} #| Remove-Item -Recurse -Force} 
if ($_.CreationTime -le $(Get-Date).AddDays(-$oldTime)) 
{ 
Remove-Item -Recurse -Force 
} 
elseif ($_.CreationTime -le $(Get-Date).AddDays(-$old2Time)) 
{ 
Remove-Item -Recurse -Force 
} 
} 
# deleting the old files 

,當我有它只是檢查單的時間和刪除任何舊的工作之前。但是現在我想要檢查是否存在超過一定天數的任何文件,然後刪除它們。如果不是,則檢查比另一天多的時間。但是當我運行它,我得到「小命令刪除,項目在命令管道位置以下參數1個 供應值: 路徑[0]:」

有誰知道什麼即時做錯了什麼?謝謝

回答

0

我把你的日期範圍放在一個數組中,並迭代這些日子。將您的日子添加到$ dayList數組中,並將您的路徑添加到$ paths數組中。這應該做你想做的。

$daysList = @(25,10) 
$paths = @("C:\Test") 

function removeOldItems($days) 
{ 
    $items = Get-ChildItem $path -Recurse -Include "*.txt", "*.docx", "*.xlsx" | WHERE {($_.CreationTime -le $(Get-Date).AddDays($oldTime))} 
    if ($items) 
    { 
     $items | Remove-Item -Force 
    } 
    return $items 
} 


foreach($path in $paths) 
{ 
    foreach ($days in $daysList) 
    { 
     Write-Host "Trying to delete files older than $days, in the folder $path" -ForegroundColor Green 
     $items = removeOldItems($oldTime) 
     if (!$items) 
     { 
      Write-Host "Did not remove anything." 
     } 
     else 
     { 
      Write-Host "Removed $($items.Count) items!" 
     } 
    } 
} 
+0

ahhh非常感謝你!我現在看到你做了什麼。沒有意識到powershell是這個複雜的。再次感謝! – user2725926

3

你打電話給刪除項目,但你永遠不會告訴它要刪除什麼。您需要爲其提供要刪除的文件的路徑/名稱。也沒有理由使用-Recurse參數。

+0

ahh ok。那麼我該如何去除它那些比那些日子更早的物品。沒有指定確切的名字。因爲名字不會總是一樣的。 – user2725926

+0

你有$ _變量中的文件對象。我會建議使用它。 – EBGreen

+0

Remove-Item -Path $ _。FullName -Force – Mitul