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

File 遍历文件夹并检查某个文件是否存在,file,powershell,loops,directory,exists,File,Powershell,Loops,Directory,Exists,我被问到以下问题:遍历文件夹列表,然后遍历子文件夹列表,最后检查每个子文件夹上是否有名为“can_erase.txt”的文件。如果文件存在,我必须读取它,保存一个参数并删除相应的文件夹(不是主文件夹,而是包含该文件的子文件夹) 我开始使用for循环,但是文件夹的名称是随机的,我遇到了一个死胡同,所以我想我可以使用foreach。有人能帮我吗 编辑:我的代码仍然非常基本,因为我知道父文件夹的名称(它们被命名为stream1、stream2、stream3和stream4),但它们的子文件夹是随机命

我被问到以下问题:遍历文件夹列表,然后遍历子文件夹列表,最后检查每个子文件夹上是否有名为“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
作为
删除项的参数,这样您就可以看到它会做什么


经过深思熟虑后的奖励:

$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
}
文件:


请向我们展示您的尝试(即您的代码),并解释实际行为与您预期的不同。我们是来帮忙的,但是你需要先给我们一些东西来帮你。我们不会为您编写代码。谢谢@AnsgarWiechers,我已经在原始帖子中附上了代码。Cheers变量名
$folder/$subfolder
不会阻止gci也迭代文件。@LotPings您是正确的。在我的替代方案中,我使用了正确的开关,但这仍然是一个问题,因为我无法跟上您的快速变化;-)@LotPings失败得很快@非常感谢你,我是Powershell的新手,你的回答真的启发了我。干杯