How to write a PowerShell function to get directories? How to write a PowerShell function to get directories? powershell powershell

How to write a PowerShell function to get directories?


Try this:

# nouns should be singular unless results are guaranteed to be plural.# arguments have been changed to match cmdlet parameter typesFunction 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.


In PowerShell 3.0, it is baked in with -File -Directory switches:

dir -Directory #List only directoriesdir -File #List only files


The answer Oisin gives is spot on. I just wanted to add that this is skirting close to wanting to be a proxy function. If you have the PowerShell Community Extensions 2.0 installed, you already have this proxy function. You have to enable it (it is disabled by default). Just edit the Pscx.UserPreferences.ps1 file and change this line so it is set to $true as shown below:

GetChildItem = $true # Adds ContainerOnly and LeafOnly parameters                      # but doesn't handle dynamic params yet.

Note the limitation regarding dynamic parameters. Now when you import PSCX do it like so:

Import-Module Pscx -Arg [path to Pscx.UserPreferences.ps1]

Now you can do this:

Get-ChildItem . -r Bin -ContainerOnly