Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does this syntax do: | select @{E={$_.PSComputerName}; L='Server'}, Name, ProcessId, PathName?

I have a Powershell script where there's a line:

$MyServers | select @{E={$_.PSComputerName}; L='AX Server'}, Name, ProcessId, PathName

What is the significance/function of this part? What does it do? Where can I understand the notation?

@{E={$_.PSComputerName}; L='AX Server'}

like image 358
William YK Avatar asked Aug 16 '26 08:08

William YK


2 Answers

While Viet's answer is not technically wrong, it doesn't really explain why that hashtable is being created as a parameter of the Select-Object.

It's generally referred to as a calculated property and it's used to customize the output of the object(s) you're selecting from. In your case, it's basically being used to rename an output column from PSComputerName to AX Server.

The L key of the hashtable is short for Label and the E key is short for Expression. So it is equivalent to writing this:

@{ Label='AX Server'; Expression={$_.PSComputerName} }

In other words, output a column called AX Server with a value that equals the PSComputerName property of the current object in the list ($_).

Calculated properties are often used to manipulate the data instead of just renaming columns. So you can do things like change the PSComputerName to upper case, do math on numeric values, or even combine multiple columns into one.

like image 134
Ryan Bolger Avatar answered Aug 17 '26 22:08

Ryan Bolger


It creates a hashtable object where the key E will be populated with PSComputerName value from $MyServers and L will be 'AX Server'

PS C:\> @{E='Value 1'; L='Value 2'} | % { write-host $_.L }
Value 2

PS C:\> @{E='Value 1'; L='Value 2'} | Select-Object -Property *

IsReadOnly     : False
IsFixedSize    : False
IsSynchronized : False
Keys           : {L, E}
Values         : {Value 2, Value 1}
SyncRoot       : System.Object
Count          : 2

PS C:\> @{E='Value 1'; L='Value 2'} | % { write-host $_.GetType().FullName }
System.Collections.Hashtable
like image 36
vhoang Avatar answered Aug 17 '26 22:08

vhoang