Reputation: 5752
When I run this command:
$k = Get-Process | select Name -First 3
I'm getting this output:
Name ---- AESTSr64 ApplicationFrameHost BtwRSupportService
I want to place each result in a separate variable of type string and get its length. I want to know how can I access individual rows returned.
I tried a foreach as follows:
foreach ($k in $three) {
write $k
}
to get
Name ---- AESTSr64 ApplicationFrameHost BtwRSupportService
I want to output only the result without the headers and the dashes and show the length of each string on the same line (when I convert the input using .ToString()
I get empty string and zero length because each result is treated as an object).
I tried this, but it produced the wrong lengths:
foreach ($k in $three) {
$t = $k | Out-String
write ("{0} {1}", $t, $t.Length)
}
So how can I produce something like this:
AESTSr64 08 ApplicationFrameHost 20 BtwRSupportService 18
Edit
One way to get the desired result, using the answer and notes below:
$three = Get-Process | select -First 3 | ForEach-Object Name
foreach ($k in $three) {
[string]$c = "{0,-15} {1}" -f $k, $k.Length
Write-Host $c
}
Upvotes: 6
Views: 13632
Reputation: 17472
you can do it simply :)
get-process | select Name, @{Name="NameLength";expression={$_.Name.length}} -first 3
if you want loop on result:
$list=get-process | select Name, @{Name="NameLength";expression={$_.Name.length}} -first 3
foreach ($item in $list)
{
write-host ("{0} {1}" -f $item.Name, $item.NameLength)
}
Upvotes: 13
Reputation: 6874
I want to place each result in a separate variable of type string and get its length. I want to know how can I access individual rows returned.
You can store the result in a variable, but typically it won't have type string, it will be an array of Process objects. If you really want strings you could do this:
$p = get-process | select -first 3 | ForEach-Object name
But $p
is still an array, so it's length will be 3! You can get the length first value as $p[0].length
... Or you can break out the individual values like this:
$p1, $p2, $p3 = get-process | select -first 3 | ForEach-Object name
But note that with this last example, if more than 3 objects were to be returned, then p3
would be an array of all but the first two...
Upvotes: 2