Woody Chan
Woody Chan

Reputation: 69

Powershell variable's output

[Using ISE]

I have: '$($udvTest | Select ProcessName -Last 1)' where $udvTest contains 5 processes as members sourced from Get-Process.

I get the following 3 lines:

ProcessName
-----------
svchost

But I want only the string "svchost" as output (e.g. for further processing). What am I overlooking that this little favour asked from PS seems so hideaous?

Upvotes: 0

Views: 65

Answers (4)

Woody Chan
Woody Chan

Reputation: 69

Thanks a lot! I see now that I have to give the property, 'ProcessName' to retrieve the pure value of it. Best!

Upvotes: 0

TobyU
TobyU

Reputation: 3918

(Get-Process | Select-Object -Last 1).ProcessName

would do the trick or for your example:

$(($udvTest | Select -Last 1).ProcessName)

Upvotes: 1

boxdog
boxdog

Reputation: 8442

"PS seems so hideaous"

Actually, the fact that you see a table of information is a hint at one of the best things about PowerShell: objects. These make your life so much easier than direct text manipulation.

Anyway, one way to get the information you want is:

$udvTest[-1].ProcessName

Since $udvTest is an array, you can index into it to find the item we want. If you supply a negative index, PowerShell will count the from the end to the beginning, so [-1] means to take the last item.

The .ProcessName is another indicator you are dealing with objects and will get the value of the ProcessName property for you.

Upvotes: 0

Olaf
Olaf

Reputation: 5232

The pure Powershell way would be this:

Get-Process | Select-Object -ExpandProperty ProcessName -Last 1

or for your particular example:

$udvTest | Select-Object -ExpandProperty ProcessName -Last 1

Upvotes: 0

Related Questions