Reputation: 555
Is it possible to get multiple properties back for a command within parentheses? Consider the following code.
$service = (get-service -name 'wuauserv')
$service.Name # I get the name property back
But what If I wanted to get more than one property. For example below:
$service.Name,Status
Why doesn't this work? Is there a way to do it?
Upvotes: 0
Views: 169
Reputation:
What you are dealing with is the concept of how PowerShell handles outputting information and the pipeline. When you collect Get-Service
into the variable $service
, you are storing an object that has multiple properties.
To work with the properties of a given object (one or many) you utilize Select-Object
(docs). Whether you are dealing with that variable contents or directly with the output from Get-Service
you have to pipe the output to Select-Object
to retrieve one to many properties. You can do this multiple ways. PowerShell works on positions when it comes to parameters, so the position 0 parameter for Select-Object
is -Property
. All of the following are equivalent, and just various ways to get the same result:
$proc = Get-Service -Name mssql*
$proc | Select-Object Name, DisplayName
$proc = Get-Service -Name mssql*
Select-Object -Property Name, DisplayName -InputObject $proc
Get-Service -Name mssql* | Select-Object Name, DisplayName
If you want your variable to only contain a given set of properties then you would also utilize Select-Object
:
$proc = Get-Service -Name mssql* | Select-Object Name, DisplayName
$proc
Upvotes: 1
Reputation: 4030
When you do $Service.Name
it returns a the expanded property, how would you return the expanded property for multiple properties?
PS H:\> $Service = (Get-Service -name 'wuauserv')
PS H:\> $Service | Select-Object Name, Status
Name Status
---- ------
wuauserv Stopped
Notice how they are not an expanded property.
PS H:\> $service.Name
wuauserv
PS H:\> $service | Select-Object -ExpandProperty Name
wuauserv
Trying to expand multiple properties will end up with an error as the method cannot accept multiple arguments (Name, Status).
Upvotes: 0