PowerShell循环中如何将变量嵌入变量名?
问题描述
这段代码可以正常运行:
$puda_TBList=(isql -S $DSQuery -U $User -P $PW -w 200 -D $DB -b -i $SQLDir\Get_TBList.sql)
但我希望在FOR循环中,将变量$DB嵌入到变量名中,比如实现$($DB)_TBList这样的变量赋值,尝试了多种写法都报错,请问有没有简便可行的方法?
我尝试的错误写法:
$($DB)_TBList=(isql -S $DSQuery -U $User -P $PW -w 200 -D $DB -b -i $SQLDir\Get_TBList.sql)$($("$DB"_TBList)=(isql -S $DSQuery -U $User -P $PW -w 200 -D $DB -b -i $SQLDir\Get_TBList.sql)$($DB)_TBList)=(isql -S $DSQuery -U $User -P $PW -w 200 -D $DB -b -i $SQLDir\Get_TBList.sql)"$($DB)_TBList"=(isql -S $DSQuery -U $User -P $PW -w 200 -D $DB -b -i $SQLDir\Get_TBList.sql)
解决方案
在PowerShell中实现动态变量名赋值,有两种简便可行的方式:
方法1:使用New-Variable命令
直接通过New-Variable创建动态命名的变量,将拼接后的变量名作为参数传入即可:
New-Variable -Name "$DB`_TBList" -Value (isql -S $DSQuery -U $User -P $PW -w 200 -D $DB -b -i $SQLDir\Get_TBList.sql)
后续需要读取该变量的值时,可使用Get-Variable并指定-ValueOnly参数:
$targetValue = Get-Variable -Name "$DB`_TBList" -ValueOnly
方法2:用哈希表替代动态变量(更推荐)
哈希表的可读性和维护性远优于动态变量,还能避免全局变量空间被污染,非常适合循环场景:
# 先初始化一个空哈希表 $tbListCollection = @{} # 在循环中给哈希表赋值,键为拼接后的名称 $tbListCollection["$DB`_TBList"] = (isql -S $DSQuery -U $User -P $PW -w 200 -D $DB -b -i $SQLDir\Get_TBList.sql) # 读取值时直接通过键访问 $targetValue = $tbListCollection["$DB`_TBList"]
内容的提问来源于stack exchange,提问作者user2893271
相关产品推荐
相关产品推荐

