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*'}
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).
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.
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 .
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.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With