chum of chance
chum of chance

Reputation: 6300

Using variables to traverse an object in powershell?

I have a variables $env that I'd like to use when traversing a powershell object: myObject.$env.connectionstring

This is not working, what I want is for Powershell to evaluate it like: myObject.Production.connectionstring ... instead I'm getting an empty string / null object.

Can I accomplish what I'm trying to do?

Upvotes: 0

Views: 138

Answers (2)

Keith Hill
Keith Hill

Reputation: 201662

This should just work. It does for me on PowerShell V3 e.g.:

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

Upvotes: 0

nabrond
nabrond

Reputation: 1388

You just need to specify $myObject rather than myObject. This code snippet produces the results I think you are looking for...

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

# prints Windows
Write-Host $obj.$prop

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

Upvotes: 2

Related Questions