簡體   English   中英

保留x個文件並刪除所有其他文件 - Powershell

[英]Keep x number of files and delete all others - Powershell

我正在嘗試編寫一個腳本,它將查看一組文件夾並僅保留最后10個文件。 每個文件夾中的文件可以每天,每周或每月創建。 無論創建日期或修改日期如何,我都需要腳本來保留最近的10個副本。

使用另一篇文章我創建了下面的腳本,但它不會保留10個副本,它會保留任何不超過10天的文件。

$ftppath = "C:\Reports"
Get-ChildItem $ftppath -recurse *_Report_*.zip -force|where {$_.lastwritetime -lt (get-date).adddays(-10)} |Remove-Item -force

關於我如何調整這個工作的任何想法? 如果我使用下面的腳本它可以工作,但只有我不設置-Recurse。 如果您使用-Recurse開關,則會出現我在腳本下方列出的錯誤。

# Keeps latest 10 files from a directory based on Creation Time

#Declaration variables
$path = "C:\Reports"                               # For example $path= C:\log\*.tmp
$total= (ls $path).count - 10 # Change number 5 to whatever number of objects you want to keep
# Script
ls $path |sort-object -Property {$_.CreationTime} | Select-Object -first $total | Remove-Item -force

錯誤:Select-Object:無法驗證參數'First'的參數。 -7參數小於允許的最小范圍0.提供大於0的參數然后再次嘗試該命令。

您可以按CreationTime降序排序並跳過前10個。如果少於10個文件,則不會刪除任何文件。

gci C:\temp\ -Recurse| where{-not $_.PsIsContainer}| sort CreationTime -desc| 
    select -Skip 10| Remove-Item -Force

更新

$path = "C:\TestDir"

# Create 12 test files, 1 second after each other
1..12 | % {
    Remove-Item -Path "$path\$_.txt" -ea SilentlyContinue
    $_ | Out-File "$path\$_.txt"
    Start-Sleep -Seconds 1
}

$files = Get-ChildItem -Path $path -Recurse | Where-Object {-not $_.PsIsContainer}
$keep = 10
if ($files.Count -gt $keep) {
    $files | Sort-Object CreationTime | Select-Object -First ($files.Count - $keep) | Remove-Item -Force -WhatIf
}

准備刪除真實時, Remove-Item -WhatIf參數到Remove-Item

@Andy:我的代表太低了,無法評論,所以發布了答案。 如果您得到奇怪的結果,可能是因為您正在查看Windows資源管理器,默認情況下顯示上次修改日期而不是創建日期。 要獲得與Windows資源管理器中顯示的結果一致的結果,請將LastWriteTime替換為CreationTime,如下所示:gci C:\\ temp \\ -Recurse | 其中{-not $ _。PsIsContainer} | sort LastWriteTime -desc | 選擇-Skip 10 | 刪除項目 - 強制

如何在SQL服務器中調用此GCI命令,嘗試下面的代碼但返回錯誤

declare @deleteoldtempxe nvarchar(1000)
        set @deleteoldtempxe='powershell.exe gci '+''''+ 'I:\New folder\'+''''+' -Recurse| where{-not $_.PsIsContainer}| sort CreationTime -desc| 
    select -Skip 1| Remove-Item -Force'
    select @deleteoldtempxe

EXEC master.dbo.xp_cmdshell @deleteoldtempxe

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM