Powershell-将值传递给参数

时间:2020-04-18 16:08:13

标签: powershell

如何将值和参数一起传递?诸如。/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" }
}

1 个答案:

答案 0 :(得分:0)

让我们讨论为什么它不起作用

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

但是您说过要保留连字符和参数

所以这行

$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
相关问题