gpt4 book ai didi

file - 遍历文件夹并检查是否存在某个文件

转载 作者:行者123 更新时间:2023-12-02 23:08:49 27 4
gpt4 key购买 nike

我被询问以下内容:遍历文件夹列表,然后遍历子文件夹列表,最后检查每个子文件夹上是否有一个名为“can_erase.txt”的文件。如果文件存在,我必须阅读它,保存参数并删除相应的文件夹(不是主文件夹,而是包含该文件的子文件夹)。

我从使用for循环开始,但是这些文件夹的名称是随机的,并且陷入了死胡同,因此我认为我可以使用foreach。谁能帮我?

编辑:我的代码仍然很基本,因为我知道父文件夹的名称(它们分别命名为stream1,stream2,stream3和stream4),但是它们的子文件夹是随机命名的。

我当前的代码:

For ($i=1; $i -le 4; $i++)
{
cd "stream$i"
Get-ChildItem -Recurse | ForEach (I don't know which parameters I should use)
{
#check if a certain file exists and read it
#delete folder if the file was present
}
cd ..
}

最佳答案

在这种情况下,您将需要多个循环来获取流文件夹,获取那些子文件夹,然后解析子文件夹中的所有文件。

foreach ($folder in (Get-ChildItem -Path 'C:\streamscontainerfolder' -Directory)) {
foreach ($subFolder in (Get-ChildItem -Path $folder -Directory)) {
if ('filename' -in (Get-ChildItem -Path $subFolder -File).Name) {
Remove-Item -Path $subFolder -Recurse -Force
continue
}
}
}

替代方法是使用管道:
# This gets stream1, stream2, etc. added a filter to be safe in a situation where
# stream folders aren't the only folders in that directory
Get-ChildItem -Path C:\streamsContainerFolder -Directory -Filter stream* |
# This grabs subfolders from the previous command
Get-ChildItem -Directory |
# Finally we parse the subfolders for the file you're detecting
Where-Object { (Get-ChildItem -Path $_.FullName -File).Name -contains 'can_erase.txt' } |
ForEach-Object {
Get-Content -Path "$($_.FullName)\can_erase.txt" |
Stop-Process -Id { [int32]$_ } -Force # implicit foreach
Remove-Item -Path $_.FullName -Recurse -Force
}

默认情况下,我建议使用 -WhatIf作为 Remove-Item的参数,以便您可以看到它的作用。

经过更多思考之后的奖励:
$foldersToDelete = Get-ChildItem -Path C:\Streams -Directory | Get-ChildItem -Directory |
Where-Object { (Get-ChildItem -Path $_.FullName -File).Name -contains 'can_erase.txt' }
foreach ($folder in $foldersToDelete) {
# do what you need to do
}

说明文件:
  • Get-ChildItem
  • ForEach-Object
  • Where-Object
  • Remove-Item
  • about_Continue
  • about_ForEach
  • about_Comparison_Operators
  • System.IO.FileSystemInfo
  • 关于file - 遍历文件夹并检查是否存在某个文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50451402/

    27 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com