我在powershell中运行一个脚本
MySchema:
type: object
required: [property1, property2, property3]
properties:
property1:
type: integer
property2:
type: integer
property3:
type: integer
然后我想从输入参考值$ i
调用一个名为$ Tom的变量的值./name -i tom
这将打印:
$tom = 29
$andrew = 99
$bill = 5
Echo $i's age is $i
答案 0 :(得分:0)
在powershell中,这将是这样的:
name.ps1
的内容:
$person = $args
$ages = @{"Tom" = 23;
"Andrew" = 99;
"Bill" = 5}
$age = $ages[$person]
Write-Host "$person's age is $age"
你会这样称呼它
.\name.ps1 "tom"
$args
包含您发送给脚本的所有参数。因此,如果您按照以下方式调用脚本:.\name.ps1 "tom" "bill"
,则结果为:tom bill's age is 23 5
答案 1 :(得分:0)
我会使用哈希表,但如果您有全局变量,则可以使用以下命令:
#variables
$tom = 29
$andrew = 99
$bill = 5
#your parameter
$i = "tom"
#echo
Echo "$i's age is $((Get-Variable | ? {$_.Name -eq $i}).Value)"
答案 2 :(得分:0)
提供的替代方法。更多代码,可以说是矫枉过正,但我认为掌握PowerShell的param功能是件好事。
# PowerShell's native argument/parameter support
param(
[string]$name
)
# Create an array with Name and Age properties as hashtable.
$people = @(
@{ Name = "Tom" ; Age = 29},
@{ Name = "Andrew" ; Age = 99},
@{ Name = "Bill" ; Age = 5}
)
# Find the person by comparing the argument to what is in your array
$person = $people | Where-Object {$_.Name -eq $name}
# Single name version: If the person is found, print what you would like. Otherwise let the user know name not found
if($person -ne $null){
Write-Host "$($person.Name) is $($person.Age) years old"
}else{
Write-Host "$name not found in list."
}
<# Multiple name version : get rid of the param section
foreach ($name in $args){
$person = $people | Where-Object {$_.Name -eq $name}
if($person -ne $null){
Write-Host "$($person.Name) is $($person.Age) years old"
}else{
Write-Host "$name not found in list."
}
}
#>