Powershell, paginating output from foreach
Seems like this should be simple, but powershell is winning another battle with me. Simply wanting to output the name of all the services run开发者_运维百科ning on a system, and their executable path, and pipe that into something I can use to search through it like Less.
So far I have:
$services = get-WmiObject -query 'select * from win32_service'
foreach($service in $services){$service.Name $service.Pathname} | less
But thats giving me the "An empty pipe element is not allowed." that I seem to have come up alot. Anyone tell me how to fix this, either by outputting to a file and Ill go through it with vim, or pipe to page/less/etc so I can do quick scan (with my eyes not programically quite yet).
Try doing the following
$services | %{ $_.Pathname } | less
EDIT Add multiple to the path
$services | %{ "{0} {1}" -f $_.Pathname,$_.Name } | less
If you are using PowerShell 2.0, you might like this:
gwmi win32_service | select-object Name,PathName | ogv
ogv (Output-GridView) is a new cmdlet in 2.0.
get-wmiobject win32_service | select-object name, pathname | more
This is also powershell 2.0 and is the close to the comment above. You were just trying to use a foreach when you didn't need to in this case.
Even with the foreach, you were close to getting an output you could work with. A comma in your foreach would have generated a output like a list and you could have used the more command instead of less.
$services = get-WmiObject -query 'select * from win32_service'
foreach($service in $services){$service.Name $service.Pathname} | more
Here is another way to write this same statement.
get-WmiObject win32_service | foreach{$.Name, $.Pathname} | more
This is still not the same as my first example, but I wanted to show you how close you were.
Looks like a good reason to use foreach-object:
$services = get-WmiObject -query 'select * from win32_service'
$services|ForEach-Object {$_|Select-Object Name,Pathname}|less
Please excuse me while I oneline it:
get-WmiObject -query 'select * from win32_service' |ForEach-Object {$_|Select-Object Name,Pathname}|less
foreach-object will return an object to the pipeline based on the input object.
I'm assuming less is an alias of your own making since I don't seem to have it.
精彩评论