2

is it possible to do something like below in powershell?

$condition = "-eq 10"
$a=11

if ($a &$condition) {"yes"} else {"no"}

basically to create part of the statement outside the statement and then use it dynamically?

I am aware I can create the whole statement in variable and then run it using Invoke-Expression or as &$cmd, but I have a very long and complex if/else statement and trying to build part of it on the fly.

Hope it makes sense :)

1 Answer 1

4

Yes, if you're OK with swapping order e.g.:

C:\PS> $conditionEq10 = {param($a) $a -eq 10}
C:\PS> $a = 11
C:\PS> if (&$conditionEq10 $a) {'yes'} else {'no'}
no
C:\PS> $a = 10
C:\PS> if (&$conditionEq10 $a) {'yes'} else {'no'}
yes

You can do prefix style notation using scriptblocks {code} with PowerShell but not infix nor postfix. That's because PowerShell wants the arguments to follow the scriptblock (not before and not between).

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.