Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reference command name with dashes

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

like image 601
Peter McEvoy Avatar asked Dec 13 '11 12:12

Peter McEvoy


3 Answers

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}
like image 116
Peter McEvoy Avatar answered Nov 13 '22 16:11

Peter McEvoy


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)

like image 20
x0n Avatar answered Nov 13 '22 15:11

x0n


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
like image 2
Shay Levy Avatar answered Nov 13 '22 15:11

Shay Levy