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).
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.
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.
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.
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]
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With