How to retrieve a recursive directory and file list from PowerShell excluding some files and folders?
powershell, powershell-2.0
Solution
The Get-ChildItem cmdlet has an `-Exclude` parameter that is tempting to use but it doesn't work for filtering out entire directories from what I can tell. Try something like this:
function GetFiles($path = $pwd, [string[]]$exclude)
{
foreach ($item in Get-ChildItem $path)
{
if ($exclude | Where {$item -like $_}) { continue }
if (Test-Path $item.FullName -PathType Container)
{
$item
GetFiles $item.FullName $exclude
}
else
{
$item
}
}
}
Problem
I want to write a PowerShell script that will recursively search a directory, but exclude specified files (for example, `*.log`, and `myFile.txt`), and also exclude specified directories, and their contents (for example, `myDir` and all files and folders below `myDir`). I have been working with the `Get-ChildItem` CmdLet, and the `Where-Object` CmdLet, but I cannot seem to get this exact behavior.