nael
nael

Reputation: 29

Powershell, How to match files names with partial names stored in text file

Sorry for the dump question as I am a beginner in PowerShell. We have a lot of coming files into a directory, and they are always increasing and decreasing in that directory because it is moved to another directory after we are done from using them.

We have a priority file list in a txt file which has only partial name of the file name.

For example, for the file name:

2017-06-5---666-12-05-01.txt

In the priority list, I have the partial name as ---666---.

How can I check if the files in the folder are already in the priority list by using Powershell?

I wrote the below script since I need only the files which are older than a given time. But it is not working.

Get-ChildItem -path $Struct.Path  -filter $Struct.filter |
Where-Object {$_.CreationTime -lt $time} |
Where-Object {$_.Name -contains "*$PriorityList*"} |
ForEach-Object { $counterP++}

Upvotes: 0

Views: 2146

Answers (2)

nael
nael

Reputation: 29

I have updated your code and now it is working perfectly

Get-ChildItem -path $Struct.Path  -filter $Struct.filter |
Where-Object {$_.CreationTime -lt $time} | ForEach-Object { If($_.name -
Match $Priorfilter) { $counterP++  }

Upvotes: 1

Mikhail Tumashenko
Mikhail Tumashenko

Reputation: 1723

First of all, the file name in your example doesn't match the partial name. So let's assume that pattern is "666". If you have several patterns, you can join them in one filter:

$PriorityList = "---666---","---555---"
$PriorityFilter = $PriorityList -join '|'

Then use this filter to check Name property:

Get-ChildItem -path $Struct.Path  -filter $Struct.filter |
Where-Object {$_.CreationTime -lt $time} |
Where-Object {$_.Name -match $PriorityFilter |
ForEach-Object { $counterP++}

The -contains operator works with a collection as left operand and do not accept wildcards for matching.

Upvotes: 0

Related Questions