Reputation: 35
I am novice in PowerShell scripting and am working on a POC. I got stuck and am not able to proceed further, so I am posting my question on this site to get some ideas/answers.
The task is to compare an array of values with Regex. But I am failing to get the desired output. Here is the code I wrote till now:
$array = @('MBS\FY16\11 May\Sirius Agreements\04 Build','MBS\FY16\11 May\Sirius Agreements\05 Build')
$values = 'MBS\FY16\11 May|MBS\FY16\12 Jan'
$Splitvalues = $values.Split('|')
[regex]$Regex = ‘(?i)^(‘ + (($Splitvalues | % {[regex]::escape($_)}) –join “|”) + ‘)$’
if($array -match $Regex)
{
echo "Matched"
}
else
{
echo "notmatched"
}`
The requirement is to match with either of them from $Values. So I am splitting them with a pipe and later creating a Regex with both array values.
When I compare with the actual array of values $array, it's failing. It is always going to the else
part.
I am thinking when we use regex to match, it'll return true if the exact word matches with the source values. Or maybe I am using the wrong regex.
I just need to match only the exact part values either "MBS\FY16\11 May" or "MBS\FY16\12 June" and return the matched value or a message.
How do I solve this issue?
Upvotes: 2
Views: 2285
Reputation: 175085
You don't need to create a new [regex]
object in order to use the -match
operator:
$ValuesToFind = 'MBS\FY16\11 May','MBS\FY16\12 Jan'
$MatchPattern = ($ValuesToFind |%{ [regex]::Escape($_) }) -join '|'
Now, when you apply -match
to an array, all matching items in the array will be returned, which sounds like a perfectly good result from your question.
Thus, you can simplify the entire thing to:
$Array = 'MBS\FY16\11 May\Sirius Agreements\04 Build','MBS\FY16\11 May\Sirius Agreements\05 Build'
$ValuesToFind = 'MBS\FY16\11 May','MBS\FY16\12 Jan'
$MatchPattern = ($ValuesToFind |%{ [regex]::Escape($_) }) -join '|'
$Array -match $MatchPattern
Upvotes: 1