Powershell - using wildcards to search for filename

瘦欲@ 提交于 2021-01-22 04:58:25

问题


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*'}

回答1:


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)


来源:https://stackoverflow.com/questions/26365486/powershell-using-wildcards-to-search-for-filename

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!