Blog Stats
  • Posts - 7
  • Articles - 0
  • Comments - 7
  • Trackbacks - 0

 

Getting a Directory or File Listing From PowerShell

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


Feedback

# re: Getting a Directory or File Listing From PowerShell

Gravatar Hi Ethan,

Thanks posting this. While we don't give you this functionalty out of the box, we do proved a little bit of help. PowerShell adds an extra property to all objects emitted from Get-ChildItem named PSIsContainer. This property will be set for all providers (registry, cert store, etc.) not just the file system so it's more portable. This simplifies things a bit so you can just write

foreach ($i in Get-ChildItem c:\temp) { if ($i.PSisContainer) {$i }}

or, using the pipeline and the where-object cmdlet,

Get-ChildItem c:\temp | where {$_.PSIsContainer}

-bruce

Bruce Payette,
Microsot Corporation 11/6/2008 10:12 PM | Bruce Payette

# re: Getting a Directory or File Listing From PowerShell

Gravatar Thanks for this excellent advice! You're right that this is much more flexible.
In order to display just the name, I augmented your example using the pipeline to:

Get-ChildItem c:\temp | where {$_.PSIsContainer} | write-host

and for the script example, I specified the Name property:
foreach ($i in Get-ChildItem c:\temp) { if ($i.PSisContainer) {$i.Name }}

The goal here was to provide the same output as my original post.

Thanks again for this really important advice,
Ethan Wilansky 11/7/2008 5:31 PM | Ethan Wilansky

Post a comment





 

 

 

 

Copyright © TechnicallySpeaking