在powershell中使用变量遍历对象?

在powershell中使用变量遍历对象?,powershell,Powershell,我有一个变量$env,我想在遍历powershell对象时使用它:myObject.$env.connectionstring 这不起作用,我希望Powershell对其进行如下评估:myObject.Production.connectionstring。。。相反,我得到的是一个空字符串/null对象 我能完成我想做的吗?您只需要指定$myObject,而不是myObject。此代码段生成我认为您正在查找的结果 $obj = Get-Item C:\Windows $prop = "Name"

我有一个变量
$env
,我想在遍历powershell对象时使用它:
myObject.$env.connectionstring

这不起作用,我希望Powershell对其进行如下评估:
myObject.Production.connectionstring
。。。相反,我得到的是一个空字符串/null对象


我能完成我想做的吗?

您只需要指定
$myObject
,而不是
myObject
。此代码段生成我认为您正在查找的结果

$obj = Get-Item C:\Windows
$prop = "Name"

# prints Windows
Write-Host $obj.$prop

# prints 7
Write-Host $obj.$prop.Length

这应该行得通。它在PowerShell V3上适用于我,例如:

PS> $d = Get-Date
PS> $time = 'TimeOfDay'
PS> $d.$time.ticks
809485347258

对myObject上缺少的
$
的调用很好。我看过去了。