views:

146

answers:

1

I want to include a parent level property in a child result set in Powershell and I can't figure out how to do it. An example of what I want to do would be to include the ServerName as the first column of a pipe to get the DatabaseName and a list of Database properties of all the databases on the server similar to:

[System.Reflection.Assembly]::LoadWithPartialName('Microsoft.SqlServer.SMO') | out-null
$s = New-Object ('Microsoft.SqlServer.Management.Smo.Server') "SQLSERVER"

$s.Databases | select $s.Name, Name, AutoShrink, AutoClose

This is a simplified example of what I am trying to do, (I could easily use the Database Parent property to get the $s.Name) but I have much more complex applications where I'd like to use this similar methodology and a Parent property isn't what I am after. Also if I could alias the $s.Name to be ServerName and the $_.Name as DatabaseName it would be the ideal output.

EDIT:

I have spent two days searching for how to do this online and can't find any reference. If you happen to Google/Bing/whatever the answer, if you'd also share what you used to find it I'd be really appreciative. I generally can find the answers to stuff, but after two days I am just throwing good time after bad.

+1  A: 

Don't you want the Parent property?

$s.Databases | select Parent, Name, AutoShrink

Edit:

$s.Databases | select @{Name="ServerPlatform"; Expression={$_.Parent.Platform}}, Name, AutoShrink
Rob Farley
That works for this scenario, but I also said that I have more complex applications. I want to be able to get any property from the $s that I want, not just the Name. I just used that as a simple example because it required the least code. That doesn't solve the second half of the problem, renaming them to ServerName and DatabaseName.
Jonathan Kehayias
I must be oversimplifying it... so let's suppose you want the Platform property of the server.
Rob Farley
And... if you don't want to bother naming it, just use the curly braces: `$s.Databases | select {$_.Parent.Platform}, Name, Autoshrink`
Rob Farley
I'll give that a +1 but it doesn't solve the real problem, I want it to come from $s, not $_. :-)
Jonathan Kehayias
ok, using what you wrote, the $s.Name works in the brackets as well for the Expression. Thanks a million.
Jonathan Kehayias