我正在用Powershell做一个简短的脚本,该脚本应该删除超过60天的文本文件,但是我无法继续,因为该脚本仅删除了一大堆随机文件,我想原因是不在数组内部,这就是为什么它不能在所有文本文件上遍历的原因。
这是整个脚本:
cls
#clearscreen
$ilogs = get-childitem D:\IMPlogs -recurse
#get all items inside IMPlogs folder
$List = $ilogs | where name -like *.txt.4
#filter items having .txt.(num)
#Write-Host ($List |Format-Table| Out-String)
#list all items in the terminal
$Today = (Get-Date -UFormat %s)
#date to seconds
$ilogsD2S = [datetime]($List).LastWriteTime
#get last write time of file and conv to datetime
#}
$conv2s = (Get-Date $ilogsD2S -UFormat %s)
#conv write time to seconds
#$conv2s
#$Today
$datediff = [int](($Today-$conv2s)/(3600*24))
#substracting today's date and files write time and getting only the whole number
$datediff
Write-Host ($List | Format-Table| Out-String)
#$List | Foreach-Object {Write-Host $_}
这是我需要处理的文本文件。 (它会自动填充此文件夹中的文本文件)
答案 0 :(得分:1)
我不确定您的示例脚本,但是您可以使用两行这样的脚本来实现目标。
Ctrl+K Ctrl+I
希望有帮助!
答案 1 :(得分:1)
尝试类似这样的东西:
Get-ChildItem "c:\temp" -file | where {$_.Name -like '*.txt.?*' -and $_.LastWriteTime -le (Get-Date).AddDays(-60)} | Remove-Item
答案 2 :(得分:0)
脚本的 primary 问题是您没有遍历文件列表。 [咧嘴]接下来是您正在将日期时间对象转换为日期字符串 ...,而这些对象不能很好地相互比较。将其保留为日期时间对象,它们的确比较整齐。
这是一个想法的演示...它针对您的temp目录中已存在10天以上的*.tmp
文件。
$SourceDir = $env:TEMP
$Filter = '*.tmp'
$MaxDaysOld = 10
$Today = (Get-Date).Date
$FileList = Get-ChildItem -LiteralPath $SourceDir -Filter $Filter -File -Recurse
foreach ($FL_Item in $FileList)
{
$DaysOld = ($Today - $FL_Item.LastWriteTime).Days
if ($DaysOld -gt $MaxDaysOld)
{
# remove or comment out the next two lines to stop showing the target info
'=' * 30
'[ {0} ] is [ {1} ] days old & can be removed.' -f $FL_Item.Name, $DaysOld
# remove the "-WhatIf" to do this for real
Remove-Item -LiteralPath $FL_Item.FullName -Force -WhatIf
}
}
截断的输出...
==============================
[ hd410B2.tmp ] is [ 20 ] days old & can be removed.
What if: Performing the operation "Remove File" on target "C:\Temp\hd410B2.tmp".
==============================
[ hd412FA.tmp ] is [ 17 ] days old & can be removed.
What if: Performing the operation "Remove File" on target "C:\Temp\hd412FA.tmp".
==============================
[*...snip...*]
==============================
[ hd4FB42.tmp ] is [ 12 ] days old & can be removed.
What if: Performing the operation "Remove File" on target "C:\Temp\hd4FB42.tmp".
==============================
[ hd4FF36.tmp ] is [ 18 ] days old & can be removed.
What if: Performing the operation "Remove File" on target "C:\Temp\hd4FF36.tmp".