代码之家  ›  专栏  ›  技术社区  ›  madsantos

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

  •  1
  • madsantos  · 技术社区  · 6 年前

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

    我从使用 for 循环,但文件夹的名称是随机的,我到达了一个死胡同,所以我认为我可以使用 foreach . 有人能帮我吗?

    编辑:我的代码仍然非常基本,因为我知道父文件夹的名称(它们被命名为 流1 , 流2 , 流3 流4 )但是他们的子文件夹是随机命名的。

    我的当前代码:

    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 ..
    }
    
    1 回复  |  直到 6 年前
        1
  •  4
  •   Maximilian Burszley    6 年前

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

    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
    }
    

    文档: