JustAGuy
JustAGuy

Reputation: 5961

Getting first line of string in a variable using Powershell

This line of code:

$eventResult = Get-EventLog -Source ".net runtime" -LogName Application -Newest 1 | select -expandproperty message

Outputs a very long string into $eventResult.

What I'd like to do is grab the very first line of it.

This outputs the ENTIRE content of $eventResult:

$eventResult | select-object -first 1

However, Outputting the data into a file and then parsing it works like a charm:

$eventResult | out-file c:\output.txt
cat c:\output.txt | select-object -first 1

What am I missing here?

UPDATE: if the output is as follows:

 Line1...
 Line2...
 Line3...

Then all I want is "Line1..."

UPDATE2:

I edited the $eventResult (forgot the | select message).

Upvotes: 18

Views: 69673

Answers (2)

Andrew Cleland
Andrew Cleland

Reputation: 161

Select-Object is returning the entire content of $eventResult because the entire content of $eventResult is the first object.

For the first line to be returned by this query each line in $eventResult needs to become its own object, e.g:

$eventResult.Split([Environment]::NewLine) | Select -First 1

Upvotes: 16

Lars Truijens
Lars Truijens

Reputation: 43645

Splitting the string on newline into an array and then taking the first of the array will work, although it might not be the most efficient.

($eventResult.Message -split '\n')[0]

Upvotes: 29

Related Questions