问题描述
我正在尝试使用 [ref]
命名参数.但是,我收到一个错误:
I'm trying to use [ref]
named parameters. However, I am getting an error:
workflow Test
{
Param([Parameter(Mandatory=$true)][String][ref]$someString)
write-verbose $someString -Verbose
$someString = "this is the new string"
}
cls
$someString = "hi"
Test -someString [ref]$someString
write-host $someString
#Error: Cannot process argument transformation on parameter 'someString'. Reference type is expected in argument.
我该如何解决这个问题?
How can I fix this problem?
推荐答案
我注意到您在 [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:
- 将[ref]参数传递给函数时,需要将参数括在括号
()
中. - 在函数中使用 [ref] 参数时,请引用 $variable.value
- 从您的参数定义中删除 [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.
这篇关于如何在 PowerShell 中将命名参数定义为 [ref]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!