PowerShell: When iterating directories, PowerShell skips directories with brackets in name

While writing a short script to find empty directories in my Music folder, PowerShell was skipping directories with brackets ([,]) in the name.

Here’s the contents of the directory:

E:\TEMP\PsExample> Get-ChildItem

    Directory: E:\TEMP\PsExample

Mode                 LastWriteTime         Length Name
----                 -------------         ------ ----
d----          10/31/2021  9:22 AM                [bracketempty]
d----          10/31/2021  9:07 AM                [brackets]
d----          10/31/2021  9:22 AM                empty
d----          10/31/2021  9:08 AM                nobrackets

This is what PowerShell was returning when simply passing $_ to Get-ChildItem. It has skipped the directory name [brackets] which has a file in it.

E:\TEMP\PsExample> Get-ChildItem -Recurse -Directory |% { Get-ChildItem $_ }

    Directory: E:\TEMP\PsExample\nobrackets

Mode                 LastWriteTime         Length Name
----                 -------------         ------ ----
-a---          10/31/2021  9:08 AM              7 file2.txt

Here is how we can iterate through directories without skipping directories with brackets in the name. Note: I’m using LiteralPath instead of simply passing along $_.

E:\TEMP\PsExample> Get-ChildItem -Recurse -Directory |% { Get-ChildItem -LiteralPath $_.PSPath }

    Directory: E:\TEMP\PsExample\[brackets]

Mode                 LastWriteTime         Length Name
----                 -------------         ------ ----
-a---          10/31/2021  9:07 AM              7 file1.txt

    Directory: E:\TEMP\PsExample\nobrackets

Mode                 LastWriteTime         Length Name
----                 -------------         ------ ----
-a---          10/31/2021  9:08 AM              7 file2.txt

Finally, this is the script I use to locate empty directories:

Function Get-EmptyDirectories {
    Get-ChildItem -Recurse -Directory | ForEach-Object {
        (Get-ChildItem -LiteralPath $_.PSPath) ? $null : "$_ -> Empty"
    }
}

When run against the example directory:

E:\TEMP\PsExample> Get-EmptyDirectories
E:\TEMP\PsExample\[bracketempty] -> Empty
E:\TEMP\PsExample\empty -> Empty


Posted

in

by

Tags: