[英]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.