简体   繁体   English

Powershell 脚本参数作为变量名

[英]Powershell script parameter as variable name

I'm quite new to Powershell scripting and I have hit a bump where I obviously don't know how to ask Google the right question.我对 Powershell 脚本很陌生,我遇到了一个问题,我显然不知道如何向 Google 提出正确的问题。

I am writing a script to be called from a system that only allows me to add a single parameter to the command line, but I in fact need more values to execute the script.我正在编写一个要从系统调用的脚本,该系统只允许我向命令行添加一个参数,但实际上我需要更多的值来执行脚本。

My idea is to build a variable for each possible parameter, and then use the variable going forward (Simplified):我的想法是为每个可能的参数构建一个变量,然后使用该变量(简化):

$name1= "value1","value2","value3"
$name2= "value4","value5","value6"
$name3= "value7","vlaue8","value9"

foreach ($value in $nameX) { } 

and then call the script like: script.ps1 nameX然后调用脚本,如:script.ps1 nameX

But how to convert the parameter into the name of the corresponding variable?但是如何将参数转换成对应变量的名称呢?

Or are there easier ways...?或者有没有更简单的方法...?

You should be able to solve your problem with the Get-Variable cmdlet:您应该能够使用Get-Variable cmdlet 解决您的问题:

# The one and only argument passed: the name of a variable defined inside
# the script; e.g., 'name1'
$variableName = $args[0]

# Define the variables that the argument can refer to:
$name1= "value1","value2","value3"
$name2= "value4","value5","value6"
$name3= "value7","vlaue8","value9"

# Use Get-Variable to get a variable's value by name.
# (Error handling omitted for brevity.)
foreach ($value in (Get-Variable $variableName -ValueOnly)) { 
  # ...
}

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

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