【发布时间】:2016-09-08 20:06:29
【问题描述】:
我在 powershell 中运行一个脚本
./name -i tom
然后我想从 $i 的输入参考值中调用一个名为 $Tom 的变量的值
$tom = 29
$andrew = 99
$bill = 5
Echo $i's age is $i
这将打印:
toms age is 29
【问题讨论】:
标签: powershell
我在 powershell 中运行一个脚本
./name -i tom
然后我想从 $i 的输入参考值中调用一个名为 $Tom 的变量的值
$tom = 29
$andrew = 99
$bill = 5
Echo $i's age is $i
这将打印:
toms age is 29
【问题讨论】:
标签: powershell
在 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
【讨论】:
$args 是用于调用脚本/函数的参数的特殊值。如果你这样称呼它:.\name.ps1 "tom",$args 包含"tom"。如果你用多个值调用它.\name.ps1 "tom" "jerry",$args 包含一个带有"tom" 和"jerry" 的数组
我会使用哈希表,但如果你有全局变量,你可以使用以下:
#variables
$tom = 29
$andrew = 99
$bill = 5
#your parameter
$i = "tom"
#echo
Echo "$i's age is $((Get-Variable | ? {$_.Name -eq $i}).Value)"
【讨论】:
提供的替代方法。更多代码,可以说是矫枉过正,但我认为掌握 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."
}
}
#>
【讨论】: