It seems so obvious that getting a directory listing excluding file using the Get-ChildItem commandlet should be simple, right? Well, it is simple, but not obvious from the built-in commandlet commands. Here’s one way you can accomplish this task:
# initialize the items variable with the
# contents of a directory
$items = Get-ChildItem -Path "c:\temp"
# enumerate the items array
foreach ($item in $items)
{
# if the item is a directory, then process it.
if ($item.Attributes -eq "Directory")
{
Write-Host $item.Name
}
}
You can also return files and exclude directories with this simple change:
# initialize the items variable with the
# contents of a directory
$items = Get-ChildItem -Path "c:\temp"
# enumerate the items array
foreach ($item in $items)
{
# if the item is NOT a directory, then process it.
if ($item.Attributes -ne "Directory")
{
Write-Host $item.Name
}
}
Technically Speaking author, Ethan Wilansky