Use Parentheses with Wildcard with Get-ChildItem

Hello,

I’m having some trouble figuring out how to use open and closing parentheses in a search string.

I’m currently running a test to find any folder with “(59946)” in the name. I’ll be using a variable for the numbered portion, but all are enclosed in parentheses once I get the parentheses to work in the search.

I’ve tried a few online suggestions for escaping special characters in a double-quoted string to no avail. I understand the backtick (`) is the escape character, and others have suggested using the backslash (\). However, neither yield any results:

$folder = '59946'
$folder = (Get-ChildItem -Path $srcPath -Include "*`($folder`)*" -Recurse -Directory
$folder = (Get-ChildItem -Path $srcPath -Include "*\($folder\)*" -Recurse -Directory
$folder = (Get-ChildItem -Path $srcPath -Include "`*`($folder`)`*" -Recurse -Directory

Ultimately I’ll be running this in a foreach loop to build a simple array. Something like this:

$quizList = Get-Content "$dstPath\list_current_week.txt"
Foreach ($quiz in $quizList) {
  $current_week = (Get-ChildItem -Path $srcPath -Include "`*`($quiz`)`*" -Recurse -Directory).Fullname
  $current_week =+ $current_week
}
$current_week

I can get a basic search to work if I build out the variable several times, but this doesn’t seem like the most effective/professional way of performing this kind of search.

$folder = '59946'
$folder = "(" + $folder + ")"
$folder = (Get-ChildItem -Path $srcPath -Include *$folder* -Recurse -Directory).Fullname

Results:

Gateway Arch (Murray) (59946) - LG 3.1

Any help would be greatly appreciated…

Your last example is just building "*(59946)*" with no escape characters, and that should work fine:

PS E:\Temp\files> $srcPath = 'E:\Temp'
PS E:\Temp\files> $folder = 59946
PS E:\Temp\files> Get-ChildItem -Path $srcPath -Include "*($folder)*" -Recurse


    Directory: E:\Temp\Files\folder1


Mode                 LastWriteTime         Length Name
----                 -------------         ------ ----
d-----        07/01/2024     10:33                Gateway Arch (Murray) (59946) - LG 3.1
2 Likes

Hello Matt,

You’re absolutely correct. I don’t know why I didn’t try this first without trying to escape those parentheses.
I made the changes and ran it again:

$srcPath = '\\mynas\ar_quiz'
$folder = '59946'
(Get-ChildItem -Path $srcPath -Include "*($folder)*" -Recurse -Directory).Fullname

Returns: \\mynas\ar_quiz\Gateway Arch (Murray) (59946) - LG 3.1

Thanks again for your help Matt…

2 Likes