Peter McEvoy
Peter McEvoy

Reputation: 2926

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

Upvotes: 10

Views: 1810

Answers (3)

x0n
x0n

Reputation: 52420

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)

Upvotes: 4

Shay Levy
Shay Levy

Reputation: 126732

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

Upvotes: 2

Peter McEvoy
Peter McEvoy

Reputation: 2926

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}

Upvotes: 8

Related Questions