1

I want to use the method given in the answer of this question: PowerShell - Remove all lines of text file until a certain string is found

However I don't get my string from "Get-Content"; I get it from "Out-String". How can I convert my "Out-String" variable into a "Get-Content" format without needing to "Set-Content"/"Get-Content" a temporary file? Or how can I get the same end result without even converting?

It really hurts my brains that a "Get-Member" on the variable from either 'Out-String' or 'Get-Content' returns a TypeName of System.String but you cannot use them the same way...

Here is the simplified code I've been trying to understand - let's use that:

# Let's work with the text from 'Get-Help' output:
$myString = (Get-Help | out-string)

# I only want the text from the "SEE ALSO" section:
$cut = $myString.Where({ $_ -like ("*SEE ALSO*") },'SkipUntil')
$cut # This shows the whole thing!!! :-(
$cut | gm | findstr TypeName # says 'TypeName: System.String'

# Dirty conversion to "Get-Content" format:
Set-Content "tmp.file" -value $cut
$recut = (Get-Content "tmp.file").Where({ $_ -like ("*SEE ALSO*") },'SkipUntil')
$recut # Now this shows what I want, even though the below returns 'TypeName: System.String' as well !!!
(Get-Content "tmp.file") | gm | findstr TypeName
stackprotector
  • 10,498
  • 4
  • 35
  • 64
Chris
  • 88
  • 1
  • 11

2 Answers2

1

In this case, you do not even need Out-String, but I will stick to your example:

$myString = (Get-Help | Out-String)
$mystring -match "(?ms)^.*(SEE\sALSO.*)$" | Out-Null
$Matches[1]

The key in the regex is (?ms). m enables multi-line search and s enables wildcards to span over multiple lines (in other words: including line breaks). The result of the -match operator is piped to Out-Null to not see it in the terminal. You might want to evaluate it though. If $true, $Matches[1] will contain your desired string.

stackprotector
  • 10,498
  • 4
  • 35
  • 64
  • Thanks, but having tested that with other outputs than 'Get-Help', I find js2010's answer more reliable (and easier to understand too). – Chris Apr 07 '20 at 07:44
1

The problem is get-help (with no parameters) or out-string is outputting one multiline string (with windows line endings). I even tried out-string -stream. This is unusual for a powershell command. Get-content would split up the lines for you automatically.

(get-help).count

1

One way to resolve it is to split on the line endings. I'm also skipping blank lines at the end. (This split pattern works with unix/osx text too.)

((get-help) -split '\r?\n').Where({ $_ -like '*SEE ALSO*' },'SkipUntil') | where { $_ } 

  SEE ALSO:
      about_Updatable_Help
      Get-Help
      Save-Help
      Update-Help

Or:

((get-help) -split '\r?\n').Where({ $_ -match 'SEE ALSO' },'SkipUntil').Where{ $_ }
js2010
  • 23,033
  • 6
  • 64
  • 66