Search code examples
powershellfilterget-childitem

Search Directory for specific file type and return true or false if it exists in PowerShell


Now this is probably a very simple fix, but I can't seem to get it. I'm trying to search a directory and it's sub-folders for a specific file type. My code currently returns as true if the file exists, but I'm trying to also have it return false on the terminal. Below is my code

Get-ChildItem "$ScriptPath\$kit" -recurse -include "*.pem"| ForEach-Object {Test-Path $_}

Now this will return as true on the terminal for the folder that does have the PEM file. But I'd like to have it also return as false on the terminal for the folder that doesn't have the file, as I am planning on using the true and false to perform different sets of code.


Solution

  • $s = 'C:\Users\user\Desktop\Source'
    
    foreach ($d in (Get-ChildItem -Recurse $s -Directory:$true)) {
        if ($d.GetFiles('*.pem')) { 
            $true 
        } else { 
            $false 
        }
    }
    

    This should get you started... I really wish PowerShell had a built-in ternary construct...