0

Right now I'm reading a File from line to line, and searching a string in it.

If I found a right Line, I just needed 1 word from the String, so I could delete everything but that string. Now I have multiple Strings int the Line which are separated by Spaces. The Problem is that the Line has a lot of spaces at the start so I can't split the sentence or remove all spaces because then the multiple words would merge to one. Here's an example:

Some Lines in the File for example:

Network 1:
              protocols ping ssh icmp
              names PC001 PC002 PC003
Network 2:
              protocols ping ssh icmp
...

Code:

Get-Content $file | ForEach-Object{
    $line = $_
    if($line -like "*protocols*"){
        $Protocols = $line.Replace("protocol ", "")
        $Protocols = $Protocol.Replace(" ", "")
    }
}

I know it isn't the best but I'm open to improvements.

2 Answers 2

1

Replace the line:

$Protocols = $Protocol.Replace(" ", "")

With:

$Protocols = $Protocol.trimstart().trimend()
Sign up to request clarification or add additional context in comments.

1 Comment

Ok maybe I should've made it more clear, the file is Huge, and there are multiple "protocls" in there. All this is inside a function that gets the Line i need. I can't take the whole File.
0

This is easy:

$file = 'D:\test\regtest.txt'

$reader = [System.IO.File]::OpenText( $file )
while( ($line = $reader.ReadLine()) -ne $null ) {
    if( $line -like '*protocols*' ) {
        $result = $line -replace '^.*protocols +(.*)', '$1' | ? { $_ } 
        $result
    }
}
[void]$reader.Close()

3 Comments

Ok maybe I should've made it more clear, the file is Huge, and there are multiple "protocls" in there. All this is inside a function that gets the Line i need. I can't take the whole File.
Thank you for the new approach, but I have a Question, what exactly is the difference between Foreach and the [System.IO.File] you use?
System.io is the fastest method for file access. if you handle with huge files, it's recommended.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.