繁体   English   中英

使用Powershell删除旧文件

[英]Deleting old files using 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

它在我只检查一次并删除任何较旧的内容之前就起作用了。 但是,现在我希望它检查是否存在任何早于特定天数的文件,然后将其删除。 如果不是,则检查是否超过另一个天数。 但是,当我运行它时,我得到“ cmdlet Remove-Item在命令管道位置1的以下参数的值:Path [0]:”

有人知道我在做什么错吗? 谢谢

您正在调用Remove-Item,但从未告诉它要删除什么。 您需要为其指定要删除的文件的路径/名称。 同样,没有理由使用-Recurse参数。

我将您的日期范围放置在数组中,并在这些天中进行迭代。 将您的日子添加到$ 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!"
        }
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM