Powershell Get-ChildItem Odd Behavior
In this article, we will be discussing an odd behavior observed when using the Get-ChildItem cmdlet in PowerShell. This behavior is related to filtering and recursion, and can lead to unexpected results if not properly understood.
The Observed Behavior
Consider the following command:
gci C:\tools\*-filter b\*.jar -recurse | select fullname
This command is supposed to list all .jar files in the C:\tools\ directory and its subdirectories, whose names start with the letter b. However, the actual result returned by this command may not be what one would expect.
Understanding the Behavior
To understand this behavior, it is important to first understand the way PowerShell processes wildcard characters in file paths.
When a wildcard character is used in a file path, PowerShell searches for matching files using the following order of priority:
- Exact name match
- Prefix match
- Suffix match
- Full match
For example, if we have the following files in the C:\tools\ directory:
a.jarb.jarc.jarba.jarbc.jar
The command
gci C:\tools\*-filter b\*.jar -recurse | select fullname
will first look for an exact match of *-filter b\*.jar. Since no such file exists, it will then look for a prefix match. In this case, the files b.jar and ba.jar match the prefix *-filter b\*.jar, and will be returned.
This behavior can lead to unexpected results if one is not aware of it. For example, if we wanted to list all .jar files in the C:\tools\ directory and its subdirectories, whose names start with the letter b, the following command would be more appropriate:
gci C:\tools\b*\*.jar -recurse | select fullname
References
- Get-ChildItem (Microsoft)
- Understanding Get-ChildItem cmdlet in PowerShell (Educba)
- About Wildcards (Microsoft)