Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting first line of string in a variable using Powershell

Tags:

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).

like image 338
JustAGuy Avatar asked Mar 08 '16 15:03

JustAGuy


People also ask

How do I extract part of a string in PowerShell?

When you want to extract a part of a string in PowerShell we can use the Substring() method. This method allows us to specify the start and length of the substring that we want to extract from a string.

How do I get the content of a variable in PowerShell?

The Get-Variable cmdlet gets the PowerShell variables in the current console. You can retrieve just the values of the variables by specifying the ValueOnly parameter, and you can filter the variables returned by name.

How do I get strings in PowerShell?

You can use Select-String similar to grep in UNIX or findstr.exe in Windows. Select-String is based on lines of text. By default, Select-String finds the first match in each line and, for each match, it displays the file name, line number, and all text in the line containing the match.


2 Answers

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]
like image 97
Lars Truijens Avatar answered Oct 19 '22 12:10

Lars Truijens


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
like image 44
Andrew Cleland Avatar answered Oct 19 '22 10:10

Andrew Cleland