繁体   English   中英

Powershell - 将值传递给参数

[英]Powershell - pass a value to parameter

如何将值与参数一起传递? 就像是。 /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" }
}

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM