powershell中的动态变量和值分配 [英] Dynamic variable and value assignment in powershell
本文介绍了powershell中的动态变量和值分配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何在运行时声明变量并为其赋值.
How can I declare variables and assign values to them at run time.
原因:我从 sql server 获取这些变量值,这些变量值本质上是可配置的
Reason: I am fetching these variables values from sql server and these variable values are configurable in nature
到目前为止我尝试过的代码
[array]$varArray = @($($ServerName),$($HostName))
foreach($varname in $varArray)
{
$varname = "some test value"
}
Write-Host $ServerName
Write-Host $HostName
推荐答案
使用动态命名变量的最简单方法是使用字典:
The simplest way of using dynamically named variables would be a dictionary:
$vars = @{} # create empty dictionary
# add key/value pairs to dictionary:
$vars["foo"] = 23
$vars["bar"] = "foobar"
$vars["baz"] = Get-Content C:\sample.txt
另一种方法是动态声明变量:
Another way would be to declare variables on the fly:
$name = "foo"
$value = "bar"
New-Variable $name $value
echo $foo
或者,您可以创建一个自定义对象并按照 Kyle C 的建议添加属性.这种方法类似于字典,但在技术上有所不同.
Or you could create a custom object and add properties as Kyle C suggested. That approach is similar to a dictionary, although technically different.
这篇关于powershell中的动态变量和值分配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文