Matching strings in PowerShell

Question:

The gist of this question is:

So it seems that if ($C -match $b.Name) considers a partial match of a string a match? Is there a better way to force a complete [match] of a string?

I’ve got a directory that gets populated with a ton of .7z files. I need to clean this directory constantly. There is another script, that predates my employment here, that’s currently working, but it’s made up of 3000 lines and generates incorrect matches constantly and doesn’t log what moved or what was deleted. Part of what makes it so big is that it has a ton of paths for where these files need to be moved to hard coded in it. Occasionally, these paths change and it’s a pain in the butt to update.

So I’ve started making a much smaller script that has all these paths referenced in a CSV file. In addition to these paths, the CSV file also has known filenames recorded in it.

I’m trying to match the file names against the recorded names in my CSV file. It generally works, but sometimes I get incorrect matches.

Let’s say I have two files that start similarly, Apple and Apple_Pie. Apple will match to Apple and move to the right directory, but Apple_Pie will first match to Apple and move to the wrong directory. Before the $C variable is cleared out it will match Apple_Pie to the right directory, but by that point Apple_Pie no longer exists in the original directory it needs to be moved from.

So it seems that if ($C -match $b.Name) considers a partial match of a string a match? Is there a better way to force a complete of a string?

I assume that I’m a bit off with my expectations of how -matchshould work.

The regex stuff I have here is to strip each file name of the date-time that gets added to the file name by another automated process. I use this to isolate the file name I want to match.

Answer:

I think your main problem is that you are using “match”.

It checks if the right string is … part of the left one, not whether it’s an actual match as you would expect.

I would replace -match with -like.

Source:

Matching strings in PowerShell by licensed under CC BY-SA | With most appropriate answer!

Leave a Reply