Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Match strings stored in variables using PowerShell

I am attempting to create a backup script that will move files that are older that 30 days, but I want to be able to exclude folders from the list

$a = "C:\\Temp\\Exclude\\test"
$b = "C:\\Temp\\Exclude"

if I run the following:

$a -match $b

Following PowerShell Basics: Conditional Operators -Match -Like -Contains & -In -NotIn:

$Guy ="Guy Thomas 1949"
$Guy -match "Th"

This returns true.

like image 844
Chadit Avatar asked Jan 17 '23 19:01

Chadit


1 Answers

I'd say use wilcards and the like operator, it can save you a lot of head aches:

$a -like "$b*"

The match operator is using regex pattern and the path is having regex special characters in it (the escape characeter). If you still want to use -match - make sure to escape the string:

$a -match [regex]::escape($b)

This will work but keep in mind that it can match in the middle of the string, you can add the '^' anchor to tell the regex engine to match from the begining of the string:

$a -match ("^"+[regex]::escape($b))
like image 155
Shay Levy Avatar answered Jan 29 '23 14:01

Shay Levy