我只想删除一个特定文件夹中超过15天前创建的文件。我如何使用PowerShell做到这一点?


当前回答

试试这个:

dir C:\PURGE -recurse | 
where { ((get-date)-$_.creationTime).days -gt 15 } | 
remove-item -force

其他回答

$limit = (Get-Date).AddDays(-15)
$path = "C:\Some\Path"

# Delete files older than the $limit.
Get-ChildItem -Path $path -Force | Where-Object { !$_.PSIsContainer -and $_.CreationTime -lt $limit } | Remove-Item -Force -Recurse

这将删除旧文件夹和它的内容。

Esperento57脚本在较旧的PowerShell版本中无法运行。这个例子是:

Get-ChildItem -Path "C:\temp" -Recurse -force -ErrorAction SilentlyContinue | where {($_.LastwriteTime -lt  (Get-Date).AddDays(-15) ) -and (! $_.PSIsContainer)} | select name| Remove-Item -Verbose -Force -Recurse -ErrorAction SilentlyContinue
#----- Define parameters -----#
#----- Get current date ----#
$Now = Get-Date
$Days = "15" #----- define amount of days ----#
$Targetfolder = "C:\Logs" #----- define folder where files are located ----#
$Extension = "*.log" #----- define extension ----#
$Lastwrite = $Now.AddDays(-$Days)

#----- Get files based on lastwrite filter and specified folder ---#
$Files = Get-Childitem $Targetfolder -include $Extension -Recurse | where {$_.LastwriteTime -le "$Lastwrite"}

foreach ($File in $Files)
{
    if ($File -ne $Null)
    {
        write-host "Deleting File $File" backgroundcolor "DarkRed"
        Remove-item $File.Fullname | out-null
    }
    else {
        write-host "No more files to delete" -forgroundcolor "Green"
    }
}

下面的代码将删除文件夹中超过15天的文件。

$Path = 'C:\Temp'
$Daysback = "-15"
$CurrentDate = Get-Date
$DatetoDelete = $CurrentDate.AddDays($Daysback)
Get-ChildItem $Path -Recurse  | Where-Object { $_.LastWriteTime -lt $DatetoDelete } | Remove-Item

给出的答案将只删除文件(无可否认,这是本文标题中的内容),但这里有一些代码将首先删除所有超过15天的文件,然后递归删除可能遗留的任何空目录。我的代码还使用-Force选项删除隐藏和只读文件。另外,我选择不使用别名,因为OP对PowerShell来说是新的,可能不理解gci、?、%等是什么。

$limit = (Get-Date).AddDays(-15)
$path = "C:\Some\Path"

# Delete files older than the $limit.
Get-ChildItem -Path $path -Recurse -Force | Where-Object { !$_.PSIsContainer -and $_.CreationTime -lt $limit } | Remove-Item -Force

# Delete any empty directories left behind after deleting the old files.
Get-ChildItem -Path $path -Recurse -Force | Where-Object { $_.PSIsContainer -and (Get-ChildItem -Path $_.FullName -Recurse -Force | Where-Object { !$_.PSIsContainer }) -eq $null } | Remove-Item -Force -Recurse

当然,如果您想在实际删除它们之前查看哪些文件/文件夹将被删除,您只需在两行末尾的Remove-Item cmdlet调用中添加-WhatIf开关。

如果你只想删除15天内没有更新的文件,而不是15天前创建的文件,那么你可以使用$_。LastWriteTime而不是$_.CreationTime。

这里显示的代码与PowerShell v2.0兼容,但我也在我的博客上将此代码和更快的PowerShell v3.0代码作为方便的可重用函数展示。