Reputation: 415
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 ?
Upvotes: 1
Views: 138
Reputation: 6920
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))
Upvotes: 2
Reputation: 46720
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.
^text
text$
^text$
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?
Upvotes: 0