Author Posts

October 15, 2017 at 7:58 pm

Hi Guys,

I have a text file that looks like so:

[Engine0]
Host=Server01
Port=11000

[Engine1]
Host=Server02
Port=12000

[Engine2]
Host=Server03
Port=13000

I tried

Select-String -Path file.txt -Pattern "Host=" -Context 1,1

which gives me the desired output but a side effect of Select-String is the filename and line number is included in the output. How can I make my output appear the same as above using the -Context parameter? Stated differently, how can I make the output look exactly like the Select-String "Line" method?

Thanks

October 15, 2017 at 10:22 pm

is this what you are looking for?

Get-Content -Path file.txt | Select-String -Pattern "Host=" -Context 1,1

  [Engine0]
> Host=Server01
  Port=11000
  [Engine1]
> Host=Server02
  Port=12000
  [Engine2]
> Host=Server03
  Port=13000

October 15, 2017 at 10:23 pm

I'm not completely sure if I got what exactly you want to get. If you're not sure what property of the result you want you can simply output all properties like this:

Select-String -Path file.txt -Pattern "Host=" -Context 1,1 | Select-Object *

If you then identified the propery you nee you can select only this like this:

Select-String -Path file.txt -Pattern "Host=" -Context 1,1 | Select-Object -Property Line

If you like to eliminate even the header you can do this:

Select-String -Path file.txt -Pattern "Host=" -Context 1,1 | Select-Object -ExpandProperty Line

October 15, 2017 at 10:42 pm

That works!

Get-Content -Path file.txt | Select-String -Pattern "Host=" -Context 1,1 | Out-File tempHost.txt
(Get-Content tempHost.txt).TrimStart(">")

Anybody know a cleaner way to do that?

Thanks for the solution Naw Awn.

October 17, 2017 at 2:57 am

The way I'm reading it, it sound like you're looking for something more like this.

Select-String -Path "D:\New Text Document.txt" -Pattern "Host=" -Context 1,1 |
ForEach-Object {
    $_.Context.PreContext
    $_.Line
    $_.Context.PostContext
}

October 18, 2017 at 4:10 pm

Yeah this works too. Thanks!