Way to use powershell params in comparison?

143 Views Asked by At

I have some ps code, that downloads xml via http and check some xml in it

[xml]$stuff = $wc.DownloadString('url') 

$xmlvalue = $stuff.SelectSingleNode('xpath') 

if ($xmlvalue.'#text' -eq "value")

{
$state = 'OK'
Write-Host 'ok'    
}

All i need is an ability to run that script as

script.ps1 -url -xpath -operator -value

It`s no problem at all, except -operator

I can`t use param like -operator "-eq", because it will be an error

Any way to do it ?

2

There are 2 best solutions below

0
On

I feel like you could simplify this if you just used regex instead. Then you don't have to worry about dynamic operators. You are just doing string comparisons so you can get the equivalent of -like -match and -eq with the right pattern.

if ($xmlvalue.'#text' -match $pattern){
    $state = 'OK'
    Write-Host 'ok'    
}

I would leave the if condition just like that. The $pattern is what you would change.

  • Starts with: ^text
  • Ends with" text$
  • Is equal to: ^text$
  • String contains: text

Just need to be careful where regex metacharacters are concerned. You can always use the regex escape method so you don't have to worry about those. So a simple string contains example would be this:

$pattern = [regex]::escape("c:\temp")

Possible learning curve with regular expression but it is a powerful thing to know. Have a look at this question which covers what I am about to show you. Specifically the answer and where that covers anchors.

Reference - What does this regex mean?

3
On

You can generate scriptblock on the fly:

Param
(
    [string]$Url,

    [string]$Xpath,

    [ValidateSet('eq', 'ne', 'like')]
    [string]$Operator,

    [string]$Value
)

[xml]$stuff = $wc.DownloadString('url') 

$xmlvalue = $stuff.SelectSingleNode('xpath') 

$ScriptBlock = @'
    if($xmlvalue.'#text' -{0} "value")
    {{
        $state = 'OK'
        Write-Host 'ok'    
    }}
'@ -f $Operator

. $([scriptblock]::Create($ScriptBlock))