Reference command name with dashes

你。 提交于 2019-12-07 00:10:15

问题


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


回答1:


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}



回答2:


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)




回答3:


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


来源:https://stackoverflow.com/questions/8489060/reference-command-name-with-dashes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!