0

I'm trying to reference an object property without using Get-Variable.
Anybody know how to do that?

$myObject = New-Object -TypeName PSObject -Property @{
    url                = 'TESTURL'
    webResponse        = ''
}

$objName = 'myObject'

Write-Host Attempt1
(Get-Variable -Name $objName -ValueOnly).url     # this works, yields TESTURL.

Write-Host Attempt2 
$($objName).url    # this fails, $($objName) returns a string instead of an object

I was expecting $($objName) to return an object, but it returns a string instead.

1
  • Well, of course, $objName is the name of your object. $myObject.url should work though. Commented Oct 25, 2016 at 12:24

1 Answer 1

2

$objName is string, you defined it yourself as a string. What you do with Get-Variable is getting a variable which is called myObject. The value that you got from Get-Variable is the actual variable of correct type. As pointed already, $myObject.url will work.

Compare it to let's say word apple and the actual fruit

Sign up to request clarification or add additional context in comments.

3 Comments

I know $myObject.url will work. But the thing is that I have a number of objects that have an URL property. I also have an array with the object names. I'd like to loop over those names and access the corresponding objects, setting the URL. Preferably without using Get-Variable. Is there no other way?
Nothing is stopping you from doing $variable1 = Get-Varable $name1 and then $variable1.property
You can also use an array of vars or a dictionary and loop

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.