简体   繁体   English

PS-如何从文本文件中删除文件名条目

[英]PS - How can I remove a file name entry from a text file

I get a list of extracted files without their full path. 我得到了没有完整路径的提取文件列表。 They come in a txt file on seperate lines. 它们放在单独行中的txt文件中。 These files can be found in different folders or subfolders. 这些文件可以在其他文件夹或子文件夹中找到。 I'd like to delete the files from the list and remove the file name from the list only if they're older than 30 minutes. 我只想从列表中删除文件,并且仅在它们早于30分钟时才从列表中删除文件名。

list.txt example: list.txt示例:

file1.doc
file2.doc
file3.doc

Let's say file3.doc is less than 30 minutes old. 假设file3.doc不到30分钟。 With my current code I can get as far as deleting file1.doc and file2.doc and not touch file3.doc no problem. 使用我当前的代码,我可以删除file1.doc和file2.doc,而不会碰到file3.doc没问题。 I would like my code to remove file1.doc and file2.doc from list.txt as it deletes the files. 我希望我的代码从list.txt中删除file1.doc和file2.doc,因为它删除了文件。

$Now = Get-Date
$Minutes = "30"
$TargetFolder = "C:\Test"
$LastWrite = $Now.AddMinutes(-$Minutes)

$Files = Get-Content C:\list.txt |% {get-childitem $TargetFolder -include $_ -recurse} | Where {$_.LastWriteTime -le "$LastWrite"}

foreach ($File in $Files)
    {
    if ($File -ne $NULL)
        {
        Remove-Item $File.FullName -WhatIf | out-null
        }
    }

I am a total beginner How would I go about removing the file name from the original list C:\\list.txt? 我是一个初学者,该如何从原始列表C:\\ list.txt中删除文件名?

Thank you. 谢谢。

I got it using Set-Content in the following manner. 我以以下方式使用Set-Content获得了它。 Feel free to comment if you think i'm doing something wrong, but this works me very well as it is. 如果您认为我做错了事,请随时发表评论,但这对我来说非常有效。

$Now = Get-Date
$Minutes = "30"
$TargetFolder = $args[0]
$LastWrite = $Now.AddMinutes(-$Minutes)
$List = "C:\list.txt"

$Files = Get-Content $List |% {get-childitem $TargetFolder -include $_ -recurse} | Where {$_.CreationTime -le "$LastWrite"}

foreach ($File in $Files)
    {
    if ($File -ne $NULL)
        {
        Add-Content -path C:\deleted.txt -value ((get-date).ToShortDateString() + ' - ' + (get-date).ToShortTimeString() + '  ' + $File.FullName)
        Remove-Item $File.FullName | out-null
        Set-Content -Path $List -Value (get-content -Path $List | Select-String -Pattern $File.Name -NotMatch)
        }
    }

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

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