Piers MacDonald
Piers MacDonald

Reputation: 563

Getting data between XML comments with powershell

I want to be able to be able to identify (and replace) XML elements between XML comments. E.g:

<!-- between here -->
<add key="userdefined1" value="something1" />
<add key="userdefined2" value="something2" />
<add key="userdefined3" value="something3" />
<!-- between here -->

The reason I'm using comments is because this is the web.config file from a .NET web project. The reason I'm not using custom config sections is that the application is years old and there are thousands of existing refernces to these keys so changing the way they're accessed could be a hassle.

Upvotes: 2

Views: 636

Answers (1)

Mat M
Mat M

Reputation: 1894

This may not be optimal, but it works. You have two constants here, the string and the filename.

$comment = '<!-- between here -->'
$start = $false
ForEach ($l in (Get-Content .\testfile.config)) { 
        if (-not $start -and $l -notmatch $comment) {continue}
        if (-not $start -and $l -match $comment ) { $start = $True }
        elseif ($start -and  $l -notmatch $comment) { echo $l }
        elseif ($start -and  $l -match $comment) { break }
}

As an alternative:

$comment = '<!-- between here -->'
$file = '.\testfile.config'
Select-String -pattern $comment -path $file | % { if (-not $b) { $b=$_.LineNumber} else { $e=$_.LinenUmber-2}}
Get-Content $file | Select-Object -Index ($b..$e)

Upvotes: 1

Related Questions