Skip navigation

Q. How can I create a list of all folders in a passed path in PowerShell that can then be passed to another cmdlet?

A. I had a large folder of virtual machines I had exported. Each folder was a separate machine, and I wanted to run a script to import each VM in the folder. The first step was to use PowerShell to create the list of folders. To do that, I needed to list all child items in a path then check if the item is of type directory, as shown below.

PS E:\Virtuals> b




    Directory: E:\Virtuals




Mode                LastWriteTime     Length Name
----                -------------     ------ ----
d----         4/25/2011   6:27 AM            hypervserv
d----         4/24/2011   4:34 PM            PXETest
d----         4/25/2011   6:02 AM            savdalappv01
d----         4/24/2011   4:44 PM            savdalcb01
d----         4/24/2011   4:50 PM            savdalclient2.savilltech.net
d----         4/24/2011   4:56 PM            savdalclient3.savilltech.net
d----         4/24/2011   5:02 PM            savdalclient4.savilltech.net
d----         4/24/2011   5:08 PM            savdalcm01


The next step is to pass this output to another command. For example, below I just pass it to a command to list the fullname of the directory. You could use any function you need to.
PS E:\Virtuals> Get-ChildItem e:\virtuals | Where-Object { $_.Attributes -band  [System.IO.FileAttributes]::Directory } | ForEach-Object {Write-Host $_.FullName}


E:\virtuals\hypervserv
E:\virtuals\PXETest
E:\virtuals\savdalappv01
E:\virtuals\savdalcb01
E:\virtuals\savdalclient2.savilltech.net
E:\virtuals\savdalclient3.savilltech.net
E:\virtuals\savdalclient4.savilltech.net
E:\virtuals\savdalcm01
E:\virtuals\savdaldc11
E:\virtuals\savdaldpm01
E:\virtuals\savdalex10
E:\virtuals\savdalfs01

Hide comments

Comments

  • Allowed HTML tags: <em> <strong> <blockquote> <br> <p>

Plain text

  • No HTML tags allowed.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Lines and paragraphs break automatically.
Publish