9

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*'}
Emperor XLII
  • 13,014
  • 11
  • 65
  • 75
Phil E
  • 93
  • 1
  • 1
  • 5
  • The single quotes are causing it to try to match the liter string '$date1'. Use double quotes to enable variable expansion in the string. – mjolinor Oct 14 '14 at 16:23
  • Or better yet, don't quote a variable reference that is already a string e.g. `... | Where-Object {$_.Name -like $date1}` :-) – Keith Hill Oct 14 '14 at 16:34
  • Thanks guys! It worked! I had ot use double quotes instead of single.. – Phil E Oct 14 '14 at 17:00
  • Use single quotes inside of double quotes ("'*$date1*'") if $date1 could contain embedded spaces. – mjolinor Oct 14 '14 at 17:28

1 Answers1

9

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)
GGO
  • 2,678
  • 4
  • 20
  • 42
Keith Hill
  • 194,368
  • 42
  • 353
  • 369
  • This seems like it could work. But the file name will be something like 'medical20141014-12345.txt'. So I need it to get ?yyyyMd?. So that it can find any files that contain the current date. Is that doable with -match? – Phil E Oct 14 '14 at 16:46
  • OK, I'm being an idiot today. The updated answer will work and the nature of `-match` and the resulting regex pattern, will find the date string anywhere in the filename. – Keith Hill Oct 14 '14 at 16:56