2013-08-28 65 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