I am wondering how or if I can use dynamic conditional parameters when using an IF statement in powershell?
Essentially the list of conditions could be 1 to many and I would have to build out some sort of filter, but not sure how to achieve this in powershell, or if its possible.
I created a small example of what I am trying to do, obviously in a real example the parameters would be truly dynamic.
$include = @("*dynamic*", "*text*")
$testString = "This is a string of text where I want to match dynamic conditional statements"
$filter = ""
foreach ($i in $include) {
$filter = $([string]::Format('{0} -like "{1}"', $filter, $i))
}
write-host $filter
#What I want it to do in pseduo code
#if ($testString matches $filter) { DoSomething }
#What it should literally do based on above example
if ($testString -like "*dynamic*" -and $testString -like "*text*") { write-host $testString }
This is how I got it working for anyone else who runs into problem and needs a clearer example. I basically built out the statement using a foreach loop on the contents of the array containing the parameters. If it was the first parameter it include the initial IF statement, and after loop finishes it tacks on the closing brackets and what code to run if the IF condition is met.
$include = @("*dynamic*", "*text*")
$testString = "This is a string of text where I want to match dynamic conditional statements"
$varnametocompare = '$testString'
$x = 0
$filter = ""
foreach ($i in $include) {
if ($x -eq 0) {
$filter = $([string]::Format('if({0} -like "{1}"', $varnametocompare, $i))
$x++
}
else {
$filter = $([string]::Format('{0} -or {1} -like "{2}"', $filter, $varnametocompare, $i))
}
}
$filter = $([string]::Format('{0}) {{ Write-Host {1} }}', $filter, $varnametocompare))
Invoke-Expression $filter
if ($(foreach ($i in $include) { if ($testString -notlike $i) {$false; break} } $true)) { DoSomething }