0

What I'm trying to do using PowerShell is to search a config file for a string of text with random amount of whitespace or tabs

Using

$mytext = '<add name="MyName"
                dllPath="My.dll"
                className="MyClass" />'
Select-String -Path $myfile -Pattern $mytext

I thought .replace(' ' , '') might help with the view of just taking the whitespace out. I then thought, there are loads of smarter people than me on here!

Thanks in advance

Natty

  • 3 points. `Select-String` uses regular expressions and you have control characters in your sample text that __need to be escaped__. Second `\s+` is a regex that would match variable whitespace. Where in that text are you expecting whitespace... between the attributes? Last: If this is XML or HTML you should be using a parser that would account for this for you – Matt Jul 28 '15 at 14:57
  • You should write a multiline regex that'll have `\s+` in all places where you expect whitespace in the file text. Then read your file as a single string and try matching with regexp. – Vesper Jul 28 '15 at 14:58

2 Answers2

0

If your whitespace can contain newlines, as it appears to, then I don't think you can do this with Select-String. It appears to check your pattern on a line-by-line basis which won't work if your pattern needs to span lines. In this case, you can use Get-Content to read the whole file as a single string and the -match operator e.g.:

Get-Content .\file.txt -Raw | Where {$_ -match '(?s)(name.*?dllPath)'} |
    Foreach {$matches[1]}

Note that the regex pattern uses singleline or dot matches anything mode via this directive (?s).

Keith Hill
  • 194,368
  • 42
  • 353
  • 369
0

Thank for the pointers folks.

From the info you both supplied I'm now loading an xml into a variable and parsing it.

[xml]$myfile = Get-Content "c:\myfile.config"

You can then use this to check it

IF ($myfile.name -match $matchnametothis) {Write-Host "do something exciting here"}

Thanks again, and hope this helps others.

Natty