I'm trying to put this function:
function Test-Any {
[CmdletBinding()]
param($EvaluateCondition,
[Parameter(ValueFromPipeline = $true)] $ObjectToTest)
begin {
$any = $false
}
process {
if (-not $any -and (& $EvaluateCondition $ObjectToTest)) {
$any = $true
}
}
end {
$any
}
}
into a module. I just created a new module, the my-scripts.psm1 file, which contains just the above function and import it with Import-Module <absolute path>
.
The problem is that if I use the function from the module 1..4 | Test-Any { $_ -gt 3 }
returns false, because $_
is not set to the value from the pipe.
If I define the function normally in a script and use it from there it works as expected (with $_ getting assigned the integer values).
This happens with PowerShell v4.0 under Windows 7.
That command:
& $EvaluateCondition $ObjectToTest
— does not bind anything to$_
. In absence of aparam()
block inScriptBlock
, the value of$ObjectToTest
will be bound to$args[0]
.Output:
Why does referencing
$_
work: you simply reference the$_
variable from the parent scope.The value of
$_
that you see, is a current pipeline input object, passed to theTest-Any
function.Output:
When you define
Test-Any
in module scope, then variable$_
with pipeline input toTest-Any
also got defined in that module scope and was not available outside of it.Output:
If you want to invoke a script block with some value bound to
$_
, then one way to do this would be: