【问题标题】:Powershell - pass a value to parameterPowershell - 将值传递给参数
【发布时间】:2020-08-01 04:07:48
【问题描述】:

如何将值与参数一起传递?像 ./test.ps1 -controllers 01 这样的东西。我希望脚本使用hyphen,并且还为参数传递了一个值。

这是我编写的脚本的一部分。但如果我用hyphen (.\test.ps1 -Controllers) 调用脚本,它会显示A parameter cannot be found that matches parameter name 'Controllers'.

param(
   # [Parameter(Mandatory=$false, Position=0)]
    [ValidateSet('Controllers','test2','test3')]
    [String]$options

)

我还需要向它传递一个值,然后将其用于属性。

if ($options -eq "controllers")
{
   $callsomething.$arg1 | where {$_ -eq "$arg2" }
}

【问题讨论】:

  • 那是.\test.ps1 -options Controllers.\test.ps1 Controllers
  • 好的,传递一个值呢?我应该为 $arg2 创建另一个参数吗?还是有其他方法?
  • 阅读CmdLetBinding 属性。您可以将此属性添加到函数或脚本文件。完成此操作后,您可以使用与内置 cmdlet 相同的语法调用函数或脚本文件。这包括按名称或按位置传递参数。
  • 另外,请查看This question and answer

标签: powershell


【解决方案1】:

让我们谈谈为什么它不起作用

function Test()
    param(
        [Parameter(Mandatory=$false, Position=0)]
        [ValidateSet('Controllers','test2','test3')]
        [String]$options
    )
}

参数是在脚本开始时创建并填写的变量

ValidateSet 仅在 $Options 等于 'Controllers','test2','test3' 三个选项之一时才允许脚本运行

让我们谈谈[] 到底在做什么

Mandatory=$false 表示 $options 不必是任何东西才能运行脚本。

Position=0 表示如果您输入脚本时没有使用-options,那么您输入的第一件事仍然是选项

例子

#If Position=0 then this would work
Test "Controllers"
#Also this would work
Test -options Controllers

[ValidateSet('Controllers','test2','test3')] 表示如果使用 Option 或者是 Mandatory 那么它必须等于 'Controllers','test2','test3'

听起来您正在尝试在运行时创建参数。这可以使用DynamicParam

function Test{
    [CmdletBinding()]
    param()
    DynamicParam {
        $Parameters  = New-Object System.Management.Automation.RuntimeDefinedParameterDictionary
        'Controllers','test2','test3' | Foreach-object{
            $Param  = New-Object System.Management.Automation.ParameterAttribute
            $Param.Mandatory  = $false
            $AttribColl = New-Object  System.Collections.ObjectModel.Collection[System.Attribute]
            $AttribColl.Add($Param)
            $RuntimeParam  = New-Object System.Management.Automation.RuntimeDefinedParameter("$_",  [string], $AttribColl)
            $Parameters.Add("$_",  $RuntimeParam) 
        }
        return $Parameters
    }
    begin{
        $PSBoundParameters.GetEnumerator() | ForEach-Object{
            Set-Variable $_.Key -Value $_.Value
        } 
    }
    process {

        "$Controllers $Test2 $Test3"

    }
}

DynamicParam 允许您在代码中创建参数。 上面的例子把数组'Controllers','test2','test3'变成了3个独立的参数。

Test -Controllers "Hello" -test2 "Hey" -test3 "Awesome"

返回

Hello Hey Awesome

但是你说要保留hypen和参数

所以这条线

$PSBoundParameters.GetEnumerator() | ForEach-Object{
    Set-Variable $_.Key -Value $_.Value
}

允许您定义每个参数值。像这样的轻微变化:

$PSBoundParameters.GetEnumerator() | ForEach-Object{
    Set-Variable $_.Key -Value "-$($_.Key) $($_.Value)"
}

会回来

-Controllers Hello -test2 Hey -test3 Awesome

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-09
    • 2022-01-05
    • 1970-01-01
    • 2023-03-26
    • 1970-01-01
    相关资源
    最近更新 更多