Reputation: 37
I'm trying to make a table in PowerShell with custom headers, I am able to do this with
"var" | Select @{n="First";e={"1"}}, @{n="Second";e={"2"}},@{n="Third";e={"3"}}
First Second Third
----- ------ -----
1 2 3
However, without the initial object, there is no output
Select @{n="First";e={"1"}}, @{n="Second";e={"2"}},@{n="Third";e={"3"}}
I can't tell the difference between these other than one is after a pipeline while the other isn't. Why won't this work?
Why doesn't this work?
Upvotes: 0
Views: 523
Reputation: 23743
Although the answer from @Neko answers the exact question, I think it is important to mention that the Select-Object
cmdlet is not mentioned to construct new custom objects:
Quote from the Get-Help Select-Object -Online
:
The
Select-Object
cmdlet selects specified properties of an object or set of objects.
In other words; the object needs to exist in order to select its properties.
For what you are doing with
"var" | Select @{n="First";e={"1"}}, @{n="Second";e={"2"}},@{n="Third";e={"3"}}`
you're creating a new pscustomobject
by removing all the default properties from the "Var"
(string) object and adding new properties with a hard-coded (static) expression which is a long-winded syntax and quiet expensive for building a new object.
To construct a new pscustomobject
("table"), you can simply use the constructor syntax:
[pscustomobject]@{First = '1'; Second = '2'; Third = '3'}
For legacy (prior PSv3) POwerShell versions:
New-Object PSObject -Property @{First = '1'; Second = '2'; Third = '3'}
Upvotes: 0
Reputation: 3112
The cmdlet Select-Object
(alias Select
) has one required parameter which is -inputObject
Which also happens to be the object that gets passed through the pipeline.
Select-Object -InputObject "Example" -Property @{n="First";e={"1"}}, @{n="Second";e={"2"}},@{n="Third";e={"3"}}
Will have the output
First Second Third
----- ------ -----
1 2 3
While without -InputObject
, it will not have an output because there is no input (Thanks @mklement0).
Select-Object "Example" -Property @{n="First";e={"1"}}, @{n="Second";e={"2"}},@{n="Third";e={"3"}}
# No Output
and with the pipeline, it will
"Example" | Select-Object "Example" -Property @{n="First";e={"1"}}, @{n="Second";e={"2"}},@{n="Third";e={"3"}}
First Second Third
----- ------ -----
1 2 3
The -inputObject
Parameter will usually contain the table you would like to select columns from or other things (if you are not using expressions).
Upvotes: 3