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

Iterate through folders and check if a certain file exists

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

我开始使用 for 循环,但文件夹的名称是随机的,我走到了死胡同,所以我想我可以使用 foreach。谁能帮帮我?

编辑:我的代码仍然很基础,因为我知道父文件夹的名称(它们被命名为 stream1stream2, stream3stream4) 但它们的子文件夹是随机命名的。

我当前的代码:

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
}

文档: