Per @SantiagoSquarzon's comments, one way to do this is to use Invoke-Expression
to generate a string containing a PowerShell command, and then execute it:
function Get-Test {
param(
[parameter(Mandatory=$true)]
[ValidateNotNullOrEmpty()]$varA,
[parameter(Mandatory=$true)]
[ValidateNotNullOrEmpty()]$varB,
[parameter(Mandatory=$true)]
[ValidateNotNullOrEmpty()]$op
)
$statement = IEX "'$varA' $op '$varB'"
if ($statement) {
Write-Host "One"
} else {
Write-Host "Two"
}
}
Get-Test -varA "Test1" -varB "Test1" -op "-ne"
However, you should be very careful to validate your input (especially if it's an "untrusted" source like a user interface) as it contains the same type of problem as a SQL Injection Attack - that is, you could end up running arbitrary code inside your function.
For example if $op
somehow ends up with the value "; write-host 'i didn''t mean to run this' ;"
(e.g. from unsanitised user input or a spiked input file) your function will execute the write-host
command without any errors so your output will look like this:
i didn't mean to run this
One
That might not be so bad in itself, but what if there was something more malicious in the string - e.g. "; Format-Volume -DriveLetter C ;"
- do you really want to be executing that command on your server?
One way to address this is to have a list of known operations you'll support - it's a bit more work up front, but it'll avoid the security issue with Invoke-Expression
:
function Get-Test {
param(
[parameter(Mandatory=$true)]
[ValidateNotNullOrEmpty()]$varA,
[parameter(Mandatory=$true)]
[ValidateNotNullOrEmpty()]$varB,
[parameter(Mandatory=$true)]
[ValidateNotNullOrEmpty()]$op
)
$result = switch( $op )
{
"-eq" { $varA -eq $varB }
"-lt" { $varA -lt $varB }
"-gt" { $varA -gt $varB }
# etc for any other operations you want to support
default {
throw "invalid operation '$op'"
}
}
if ($result) {
Write-Host "One"
} else {
Write-Host "Two"
}
}
If you try that with an invalid operation you'll get something like this:
PS> Get-Test -varA "Test1" -varB "Test1" -op "; write-host 'i didn't mean to run this' ;"
Exception:
Line |
19 | throw "invalid operation '$op"
| ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
| invalid operation '; write-host 'i didn't mean to run this' ;