且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在 PowerShell 中将命名参数定义为 [ref]

更新时间:2023-11-23 20:27:16

我注意到您在 [ref] 参数示例中使用了工作流程".为简单起见,我们称其为函数",稍后再回到工作流程".

I noticed that you are using a "workflow" in your example of a [ref] parameter. For simplicity, let's call it a "function" and get back to "workflow" later.

您需要在代码中更改三件事:

There are three things you need to change in your code:

  1. 将[ref]参数传递给函数时,需要将参数括在括号()中.
  2. 在函数中使用 [ref] 参数时,请引用 $variable.value
  3. 从您的参数定义中删除 [string] 类型.它可以是 [string] 或 [ref],但不能同时是两者.

这是有效的代码:

function Test
{
    Param([Parameter(Mandatory=$true)][ref]$someString)

    write-verbose $someString.value -Verbose
    $someString.value = "this is the new string"
}
cls
$someString = "hi"
Test -someString ([ref]$someString)
write-host $someString

至于工作流程".它们非常受限制,请阅读 PowerShell 工作流程:限制.特别是您不能在工作流中的对象上调用方法.这将打破这一行:

As for "workflows". They are very restricted, read PowerShell Workflows: Restrictions. In particular you can't invoke a method on an object within workflow. This will break the line:

$someString.value = "this is the new string"

由于工作流限制,我认为在工作流中使用 [ref] 参数并不实用.

I don't think that using [ref] parameters in a workflow is practical, because of workflow restrictions.