5

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.

1 Answer 1

10

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))
Sign up to request clarification or add additional context in comments.

2 Comments

the seconds and third one worked as long as I did $a[0] -match [regex]::escape($b[0]) and this now resolves as true $a[0] -match $b[0] which makes no sense to me, when I check the properties they all say system.string.... thanks
You're indexing the string and get back the first character from each variable ('C').

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.