Welcome › Forums › General PowerShell Q&A › sort before or after
- This topic has 4 replies, 4 voices, and was last updated 8 months, 2 weeks ago by
Inactive.
-
AuthorPosts
-
-
May 12, 2020 at 9:09 pm #227626
I have $output likes this (over 10000 records):
Hostname : PC0101
Clustername : ClusterA
IPaddress : 10.10.10.101
Folder : \\server\vmpath\ActiveDesktopHostname : SVR0101
Clustername : ClusterB
IPaddress : 10.10.10.121
Folder : \\server\vmpath\ActiveServer$output |Foreach-object { if($_.Hostname -match ‘^P’) {select-object -property Hostname, Clustername} }
Nothing happens
$output |select-object -property Hostname, Clustername |where {$_.Hostname -match ‘^P’}
It works.
Can someone point to me where is the issue?
-
May 12, 2020 at 10:23 pm #227629
Sam,
when you post code, error messages, sample data or console output format it as code, please.
In the “Text” view you can use the code tags “PRE“, in the “Visual” view you can use the format template “Preformatted“. You can go back edit your post and fix the formatting – you don’t have to create a new one.
Thanks in advance.Select-Object needs an InputObject. Either by pipeline or explicit. You do not provide any input object in your first code snippet. ;-} You may (re-)read the help for the cmdlet including the examples to learn how to use it.
BTW: The subject you choose does not fit your question at all in my opinion.
-
May 13, 2020 at 1:54 am #227662PowerShell123$output |Foreach-object {$_ | if($_.Hostname -match ‘^P’) {select-object -property Hostname, Clustername} }It still doesn't work.
-
May 13, 2020 at 3:52 am #227671
You still aren’t providing it input. You can’t pipe input into if. If your condition is true in your first example, the code that executes is
PowerShell1select-object -property Hostname, ClusternameThere is no input. You eat up the piped input with the foreach, now provide it back to Select-Object.
PowerShell1$output |Foreach-object { if($_.Hostname -match ‘^P’) {$_ | select-object -property Hostname, Clustername} }So many of the built in examples could’ve answered this question. It may make it easier if you name your variables explicitly.
PowerShell1foreach($item in $output){ if($item.Hostname -match ‘^P’) {select-object -inputobject $item -property Hostname, Clustername} }Hopefully this helps.
-
May 13, 2020 at 7:55 am #227698
-
-
AuthorPosts
- The topic ‘sort before or after’ is closed to new replies.