Basically I'm trying to get the below "inline if-statement" function working (credit here)
Function IIf($If, $Then, $Else) {
If ($If -IsNot "Boolean") {$_ = $If}
If ($If) {If ($Then -is "ScriptBlock") {&$Then} Else {$Then}}
Else {If ($Else -is "ScriptBlock") {&$Else} Else {$Else}}
}
Using PowerShell v5 it doesn't seem to work for me and calling it like
IIf "some string" {$_.Substring(0, 4)} "no string found :("
gives the following error:
You cannot call a method on a null-valued expression.
At line:1 char:20
+ IIf "some string" {$_.Substring(0, 4)} "no string found :("
+ ~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : InvokeMethodOnNull
So, as a more general question, how do you make $_
available to the scriptblock passed into a function?
I kind of tried following this answer, but it seems it's meant for passing it to a separate process, which is not what I'm looking for.
Update: It seems the issue is that I have the function in a module rather than directly in a script/PS session. A workaround would be to avoid putting it in the module, but I feel a module is more portable, so I'd like to figure out a solution for that.