Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Powershell - using wildcards to search for filename

I am trying to make a PowerShell script that will search a folder for a filename that contains a certain file-mask. All files in the folder will have format like *yyyyMd*.txt.

I have made a script:

[String]$date = $(get-date -format yyyyMd)
$date1 = $date.ToString
Get-ChildItem C:\Users\pelam\Desktop\DOM | Where-Object {$_.Name -like '*$date1*'}

But this does not seem to work..

Can anyone help? It seems the problem is that the date variable is not correct because when I hard code something like below, it works:

Get-ChildItem C:\Users\pelam\Desktop\DOM | Where-Object {$_.Name -like '*20141013*'}
like image 964
Phil E Avatar asked Oct 14 '14 16:10

Phil E


People also ask

How do you use a wildcard in a filename?

When you have a number of files named in series (for example, chap1 to chap12) or filenames with common characters (like aegis, aeon, and aerie), you can use wildcards (also called metacharacters) to specify many files at once. These special characters are * (asterisk), ? (question mark), and [ ] (square brackets).

How can you search a file using wildcard?

You can use the asterisk ( * ) and the question mark ( ? ) anywhere in a search, and you can also use them together. For example, if you want to find all the files that start with home , followed by one or two characters, and ending with any extension, enter home??. * as your search term.

How do I use wildcards in PowerShell?

Wildcard characters represent one or many characters. You can use them to create word patterns in commands. Wildcard expressions are used with the -like operator or with any parameter that accepts wildcards. In this case, the asterisk ( * ) wildcard character represents any characters that appear before the .

What wildcards could be used when searching for a file?

Since the very beginning, Microsoft has allowed searches using two wildcards, the asterisk (*) and the question mark (?). In general terms, the question mark is used to substitute for one letter or symbol that you don't know.


1 Answers

You can simplify this by just using regex with the -match operator:

Get-ChildItem C:\Users\pelam\Desktop\DOM | Where-Object {$_ -match (Get-Date -format yyyyMMdd)}

And if you are on V3 or higher, you can further simplify to:

Get-ChildItem C:\Users\pelam\Desktop\DOM | Where Name -match (Get-Date -format yyyyMMdd)
like image 175
Keith Hill Avatar answered Oct 11 '22 05:10

Keith Hill