如何在 PowerShell 中将命名参数定义为 [ref] [英] How to define named parameter as [ref] in PowerShell

查看:130
本文介绍了如何在 PowerShell 中将命名参数定义为 [ref]的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 [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:

  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.

这篇关于如何在 PowerShell 中将命名参数定义为 [ref]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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