Home > Net >  PowerShell: Return $PSItem/$_ Looked up Within a ForEach-Object Script Block
PowerShell: Return $PSItem/$_ Looked up Within a ForEach-Object Script Block

Time:03-10

I've been working on this problem in my personal time for days now...

I need to add a column to the results (Example issue. The code below will eventually error out. [I was just using -Include to test on a single row. My real-world problem uses a different cmdlet, but the same premise).

How do I get what the query was ran for to show up in the resulting table?

 ForEach-Object {Get-Service $_.name -DependentServices}

What I need it to look like.

Status Name DisplayName Parent Name
Stopped workfolderssvc Work Folders WSearch
Stopped WMPNetworkSvc Windows Media Player Network Sharin... WSearch
Stopped AarSvc_51453 Agent Activation Runtime_51453 AudioEndpointBuilder
Stopped AarSvc Agent Activation Runtime AudioEndpointBuilder
Running Audiosrv Windows Audio AudioEndpointBuilder

What the query returns: Status, Name, DisplayName

What I need the query to return: Status, Name, DisplayName, Parent Name

I've tried $row, making a new array by piping through to Select-Object within my Script block, and wrapping $_ in [ $_ ], " $_ ", or "[$_]".

| Select-Object Status, Name, DisplayName,  [PSCustomObject]@{Name="Parent Name";Expression={$_.name}}

I'm using Powershell 5.1.

Thank you.

CodePudding user response:

Assuming that by "Parent name", you mean that you want the services that the current service depends upon to be running, then you would do it the following way.

ServicesDependedOn is an array, so it might output more than one result.

Get-Service -DependentServices | Select-Object Status, Name, DisplayName,  @{Name="Parent Name";Expression={$_.ServicesDependedOn}} | Sort Name

You were nearly there, but the calculated property take a hashtable, not a PSCustomObject. Also, if you use $_.Name as the expression, you will just repeat the Name value you already selected so you need to target the expression you want as a value instead.

References

ServiceController class

About Calculated properties (PS 5.1)

  • Related