header
header Register : : Login header
header
divider
menuleft
menuright
submenu
left

[August 25th, 2008] Check the home page regarding PowerShell related news from a brand new sponsor: Idera

How do I access an object property using a variable value?
Last Post 20 Jun 2008 08:12 AM by stevehiner. 2 Replies.
Printer Friendly
Sort:
PrevPrev NextNext
You are not authorized to post a reply.
Author Messages
stevehinerUser is Offline
New Member
New Member
Posts:6

--
18 Jun 2008 12:28 AM  

I'm working on a script and I want to let the user pass me the name of an object's property.  Basically like Format-List and Format-Table do.  You can tell them which properties to display.  I'm sure it's possible inside a script (as opposed to a compiled cmdlet).

Something like this:

 


param([string]$propertyName)
Write-Host $_.$propertyName #that doesn't work
Write-Host $_.Property[$propertyName] #that doesn't work either

I thought about doing it with Invoke-Expression but that seemed like overkill. I'm sure there's an easier, more PowerShell-ish way to do it. I bet it's something that will seem totally obvious once I see it.

I've done the typical things with get-member to try to figure it out and I've Googled for it.  I tried searching these forums but the search feature appears to be non-functional for me.  I hope this isn't a question that's already been answered 100 times around here.

 Thanks for the help.

Steve
KarlUser is Offline
New Member
New Member
Posts:11
Avatar

--
18 Jun 2008 12:36 AM  
you are on the right track, you are just dealing with powershell parsing mode (command versus expression) . use $() to force your logic to be evaluated as an expression rather than just as a stringproperty for write-host)

Here is an example

function testprop([string]$propertyName)
{
process {
Write-Host $($_.$propertyName)
}
}

get-Process | testprop name
stevehinerUser is Offline
New Member
New Member
Posts:6

--
20 Jun 2008 08:12 AM  

Yes!  Thank you so much.  I had a feeling it was easy.  I never would have thought of that even though I've used the technique myself to call Read-Host as a default value for param arguments.  Now I understand better why that's needed - thanks for the education.

Steve
You are not authorized to post a reply.

Active Forums 4.1
right
   
footer Sponsored by Quest Software • SAPIEN Technologies • ShellTools, LLC • Microsoft Windows Server 2008 footer
footer