带破折号的参考命令名称 [英] Reference command name with dashes

查看:60
本文介绍了带破折号的参考命令名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近发现 Powershell 函数只是命名的脚本块.例如

I've recently discovered that Powershell functions are just named scriptblocks. For example

function HelloWorld {
    Write-Output "Hello world"
}

$hw = $function:HelloWorld

& $hw     

将执行 HelloWorld 方法.

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

有什么想法吗?

我知道我可以这样做:

$hw = (Get-Item function:Hello-World).ScriptBlock

但它有点嘈杂",我喜欢 $function 语法

But it's a bit "noisy" and I like the $function syntax

推荐答案

Doh!我应该坚持 程序员问题解决序列 并在我发布到 SO 之前询问我的同事.看起来我应该使用:

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}

这篇关于带破折号的参考命令名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆