Powershell - Exclude folders in Get-ChildItem

Viewed 35314

How to exclude folders ? Now I hardcode the folder names but i want it to be more flexible.

foreach($file in Get-ChildItem $fileDirectory -Exclude folderA,folderb)
5 Answers

The sipmlest way to exclude your folders recursively:

foreach($file in Get-ChildItem $fileDirectory -Exclude {Get-ChildItem folderA},{Get-ChildItem folderB})

where:

$fileDirectory - search folder

folderA, folderB - excluded folders

For future googlers, I have found that files have a property called PSIsContainer which is $true when they are a directory. A command listing all files in $fileDirectory would be:

foreach ($file in Get-ChildItem $fileDirectory | Where-Object -Property PSIsContainer -eq $false)
{
    Write-Host $file.Name
}

Note that -Property is optional for the cmdlet Where-Object.

Related