powershelldirectory-listing

Two level directory listing with Powershell


I've been trying to get a very specific directory listing with no success so far.

Lets say I have a folder structure like this:

Now, when I use foreach, it will look like this:

$folders = Get-ChildItem $UpdateDir -Directory -Recurse -Depth 1 | Select-Object FullName

ForEach($folder in $folders) {
   $folder = folder.TrimStart("@{FullName=").TrimEnd("}") #To get a clean name
}

The result will be as follows:

C:\inetpub\updates\updatefolder1
C:\inetpub\updates\updatefolder2
C:\inetpub\updates\updatefolder1\Web\
C:\inetpub\updates\updatefolder1\Web\ (site code, the structure goes on)
C:\inetpub\updates\updatefolder1\Scripts\ (db scripts)
C:\inetpub\updates\updatefolder2\Web\ (site code, the structure goes on)

Which is not ok. It should look like this:

C:\inetpub\updates\updatefolder1
C:\inetpub\updates\updatefolder1\Web\
C:\inetpub\updates\updatefolder1\Web\ (site code, the structure goes on)
C:\inetpub\updates\updatefolder1\Scripts\ (db scripts)
C:\inetpub\updates\updatefolder2
C:\inetpub\updates\updatefolder2\Web\ (site code, the structure goes on)

Any fresh ideas ? I've tried several things, other than that foreach loop, still no luck.

Thanks in advance.


Solution

  • The ForEach loop is not needed it can be replaced by -expandproperty in the select object. If I understood the question correctly, the issue that you bring up is that the results aren't sorted. The answer is to sort the results using `Sort-Object'

    Example

    $folders = Get-ChildItem $UpdateDir -Directory -Recurse -Depth 1 | 
         Select-Object -ExpandProperty fullname | 
         Sort-Object
    $folders