How to write a PowerShell function to get directories?

Tim Murphy picture Tim Murphy · Jul 17, 2010 · Viewed 13.4k times · Source

Using PowerShell I can get the directories with the following command:

Get-ChildItem -Path $path -Include "obj" -Recurse | `
    Where-Object { $_.PSIsContainer }

I would prefer to write a function so the command is more readable. For example:

Get-Directories -Path "Projects" -Include "obj" -Recurse

And the following function does exactly that except for handling -Recurse elegantly:

Function Get-Directories([string] $path, [string] $include, [boolean] $recurse)
{
    if ($recurse)
    {
        Get-ChildItem -Path $path -Include $include -Recurse | `
            Where-Object { $_.PSIsContainer }
    }
    else
    {
        Get-ChildItem -Path $path -Include $include | `
            Where-Object { $_.PSIsContainer }
    }
}

How can I remove the if statement from my Get-Directories function or is this a better way to do it?

Answer

x0n picture x0n · Jul 17, 2010

Try this:

# nouns should be singular unless results are guaranteed to be plural.
# arguments have been changed to match cmdlet parameter types
Function Get-Directory([string[]]$path, [string[]]$include, [switch]$recurse) 
{ 
    Get-ChildItem -Path $path -Include $include -Recurse:$recurse | `
         Where-Object { $_.PSIsContainer } 
} 

This works because -Recurse:$false is the same has not having -Recurse at all.