迭代文件夹并检查是否存在某个文件

时间:2018-05-21 14:51:57

标签: file powershell loops directory exists

我被问到如下:迭代一个文件夹列表,然后遍历一个子文件夹列表,最后检查每个子文件夹上是否有一个名为“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 ..
}

1 个答案:

答案 0 :(得分:4)

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

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
}

文档: