powershell - 如何在 PowerShell 中将 "named"参数定义为 [ref](这次是真的)

标签 powershell

我见过this ,但两个答案实际上都没有在调用函数时使用命名参数回答问题
这适用于 Powershell 7。没有工作流程。这次真的是命名参数!也未包含在标准文档中 here .. 开始认为这是不可能的。
这是有效的,但它需要带有位置参数的括号,而不是命名参数

Function MyFunction ([ref][string]$MyRefParam) {
    $MyRefParam.Value = "newValue";
}
$myLocal = "oldValue"
Write-Host $myLocal  # Outputs: oldValue
MyFunction ([ref]$myLocal);
Write-Host $myLocal # Outputs: newValue
当然,我们都知道调用 Powershell 函数的最佳方式是使用命名参数 MyFunction -Arg1 23而不是位置参数 MyFunction 23MyFunction(23) .这些不会通过我们的拉取请求!
但这不起作用
Function MyFunction ([ref][string]$MyRefParam) {
    $MyRefParam.Value = "newValue";
}
$myLocal = "oldValue"
Write-Host $myLocal  # Outputs: oldValue
MyFunction -MyRefParam ([ref]$myLocal) # Outputs Cannot process argument transformation on parameter 'MyRefParam'. Reference type is expected in argument.
Write-Host $myLocal # Outputs: oldValue
是否有另一种方法可以在此语法中提供 ref 类型?到目前为止,我已经在参数定义和调用中尝试了 [ref] 和 [ref][string] 的组合 - 我无法得到任何东西让 Powershell 看到我真的传递了一个 Ref
谢谢你的帮助!

最佳答案

仅使用 [ref]在参数声明中输入约束 ,即删除额外的 [string]类型约束(它不做任何事情,甚至不应该被允许 - 见底部):

Function MyFunction ([ref] $MyRefParam) {
    $MyRefParam.Value = "newValue"
}

$myLocal = 'oldVaue'
MyFunction -MyRefParam ([ref] $myLocal)
$myLocal # -> 'newvalue'
您不能输入 [ref]实例:[ref]不是修改参数声明的关键字(如 ref 在 C# 中),它本身就是一种类型, System.Management.Automation.PSReference ,及其保值属性,.Value类型为 object ,即它可以容纳任何类型的对象。
结果:
  • 当值通过 [ref] 传递时,您不能强制执行特定的数据类型。 .[1]
  • 相反,您可以自由地为 .Value 分配任何类型的值。 [ref] 的属性(property)实例收到。

  • 退一步 :
  • [ref]主要用于支持对 .NET API 的调用 ref/out参数。
  • 它在纯 PowerShell 代码中的使用是不寻常的,最好避免 ,尤其是由于笨拙的调用语法。

  • 也就是说,位置和命名参数绑定(bind)之间的双重类型约束的行为差异当然很奇怪 - 见 Mathias R. Jessen's评论中有很好的解释。
    然而,真正的问题是,您甚至可以定义涉及 [ref] 的多类型约束(本身不寻常)。 ,因为似乎有一个有意的检查来防止这种情况发生,但它并没有出现在参数声明中。
    但是,您可以使其显示如下(直接在命令行中运行):
    # ERROR, because [ref] cannot be combined with other type constraints.
    PS> [ref] [string] $foo = 'bar'
    
    Cannot use [ref] with other types in a type constraint
    
    GitHub issue #16146 中报告了在参数声明中没有强制执行相同的检查。 .

    [1] 在幕后,当实际值通过 [ref] 传递时,会使用非公开的泛型类型。 cast ( System.Management.Automation.PSReference<T> ),它使用被转换的值的任何类型实例化。然而,这个泛型类型的 .Value属性(property)还在[object] -typed,允许修改以分配任何类型。

    关于powershell - 如何在 PowerShell 中将 "named"参数定义为 [ref](这次是真的),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69306144/

    相关文章:

    powershell - Databricks API 2.0 - 使用服务主体凭据在 powershell 中创建 secret 范围

    powershell - 如何通过Powershell在不同的列中分别接收OU值?

    powershell - 如何删除 PowerShell 要求脚本和可执行文件前面带有 ".\"的要求?

    sql-server-2008 - 为什么 sqlpsx 不包含在 SQL Server 本身中?

    powershell - 在 Powershell 中比较 System.Version

    具有多个 session 的 Powershell 独立脚本

    regex - 使用 Powershell 和 Regex 从文本文件中提取行 block

    Powershell Get-ChildItem -Filter 与具有相同值的 Where 子句的操作不同

    Powershell,如何检查 AD 用户的组成员身份

    azure - Azure 中的存储消耗报告