I've recently discovered that Powershell functions are just named scriptblocks. For example
function HelloWorld {
Write-Output "Hello world"
}
$hw = $function:HelloWorld
& $hw
Will execute the HelloWorld method.
However, what I have not been able to figure out, is how to get a reference to a method that has a dash in it's name:
function Hello-World {
Write-Output "Hello world"
}
$hw = $function:Hello-World
You must provide a value expression on the right-hand side of the '-' operator.
At line:1 char:27
+ $hw = $function:Hello- <<<< World
+ CategoryInfo : ParserError: (:) [], ParentContainsErrorRecordException
+ FullyQualifiedErrorId : ExpectedValueExpression
Any ideas?
I'm aware that I could do something like:
$hw = (Get-Item function:Hello-World).ScriptBlock
But it's a bit "noisy" and I like the $function syntax
Doh! I shoulda stuck with the Programmer Problem Solving Sequence and asked my co-workers before I posted to SO. Looks like I should use:
$hw = ${function:Hello-World}
As well as using $script = ${function:hello-world}
there is also $script = get-content function:hello-world
. '$' as a unary operator equates to using get-content
(alias is gc
)
To invoke the function all you need to do is to call it by its name.
PS> Hello-World
Hello world
${function:Hello-World}
is the way to get the code of the function. Here's another way:
Get-Command Hello-World | Select-Object -ExpandProperty Definition
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With