powershell - Powershell在函数调用后忽略表达式

标签 powershell syntax expression

这是一个powershell脚本:

function PickANumber()
{
  12
}

function GetTheAnswer()
{
  PickANumber + 30
}

$answer = GetTheAnswer
write-output "The answer is $answer"

该脚本的输出为:
The answer is 12

据我猜测,发生这种情况是因为powershell函数调用的参数或逗号之间没有括号,因此PickANumber + 30被解析为PickANumber('+', 1)而不是PickANumber() + 1。这不是一个错误,未使用的args会被简单地忽略(如JavaScript)。

如果稍加更改,答案是42:
function GetTheAnswer()
{
  $a = PickANumber
  $a + 30
}

但是肯定有一种方法可以做到这一点吗?

我要在这里发帖,因为这也会咬人。

最佳答案

为了避免这种陷阱,您可以像这样定义函数

function PickANumber()
{
  [CmdletBinding()]
  param()

  12
}

执行PickANumber + 30时,您会收到错误消息

PickANumber : A positional parameter cannot be found that accepts argument '+'.

关于powershell - Powershell在函数调用后忽略表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16506899/

相关文章:

macos - macOS pwsh 出现错误 "no supported WSMan client library was found."

C编程: error: expected ‘)’ before string constant

javascript - HTML 代码 - 某些内容无效 - 无法弄清楚是什么

vim - 如何让 vim 语法高亮整行?

c# - 在对象初始化期间添加事件处理程序

c# - 表达式解析 - 可以将属性名称数组作为字符串获取吗?

C by K&R - 关系或逻辑表达式的数值

powershell - 设置 HomeDirectory 值时强制 Powershell 创建 AD 用户文件夹

azure - 流分析: Best parameters to choose for the autopause of a day wise TUMBLINGWINDOW stream job and best trigger time to set for that function

javascript - 如何使用 powershell 更改列值的格式?