Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Filtering sub-objects in PowerShell using Select-Object

Many of you are familiar with the calculated properties possible in PowerShell, to raise a property needed from a sub-object level.

I.e. if I'd like to know the owner of a process (i.e. notepad) as a non-admim I could fetch the process with WMI and query for the owner object using

Get-WmiObject -ClassName Win32_Process -Filter "name='notepad.exe'" | 
  Select-Object -Property ProcessId,Name,@{label='User'; expression={$_.GetOwner().User}}

ProcessId Name        User
--------- ----        ----
    16028 notepad.exe user01
     1972 notepad.exe user01

I could proceed with more properties as Domain

@{l='Domain'; e={$_.GetOwner().Domain}}

ProcessId Name        Domain
--------- ----        ------
    16028 notepad.exe domain01
     1972 notepad.exe domain01

I could also opt to keep the Owner object as is, if I need

@{l='Owner'; e={$_.GetOwner()}}

ProcessId Name        Owner
--------- ----        -----
    16028 notepad.exe System.Management.ManagementBaseObject
     1972 notepad.exe System.Management.ManagementBaseObject

However, how do I go about to keep the object structure while only getting select subobjects?

ProcessId Name        Owner
--------- ----        -----
    16028 notepad.exe @{User=user01; Domain=domain01}
     1972 notepad.exe @{User=user01; Domain=domain01}
like image 262
Dennis Avatar asked Feb 13 '26 11:02

Dennis


1 Answers

The answer (which is often the case with PowerShell) is really simple. Calculated properties uses a code block {my-code} that can contain any valid commands. So just use Select-Object within the expression.

Get-WmiObject -ClassName Win32_Process -Filter "name='notepad.exe'" | 
  Select ProcessId,Name,@{l='Owner'; e={$_.GetOwner() | Select User,Domain}}
like image 139
Dennis Avatar answered Feb 16 '26 06:02

Dennis



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!