Skip to content

Instantly share code, notes, and snippets.

@aadennis
Created October 30, 2017 23:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aadennis/7fcb5ab339d0fd69f9a04a48cde6a94a to your computer and use it in GitHub Desktop.
Save aadennis/7fcb5ab339d0fd69f9a04a48cde6a94a to your computer and use it in GitHub Desktop.
Walk an XML file, updating key values pairs based on a given pattern
# Having generated well-formed but invalid xml from bsa xsd, the tool that gen'd the sample xml
# may have duplicated e.g. SeqNum.
# This takes an input file ($inFile), makes the SeqNum values unique, and writes to a random named
# file in c:/temp ($outFile).
# Now when you validate e.g. in Visual Studio or XMLSpy, the SeqNum will pass (even if plenty else is wrong.)
function Set-ReplacementString($templateStart, [int] $valueToUpdate, $templateEnd) {
"$templateStart$valueToUpdate$templateEnd"
}
$inFile = Get-Content -Path C:\temp\x.xml
$inFile.Length
$pattern = "SeqNum=`".*`"" # "any and all characters within the double quotes are ignored for pattern-matching (in addition to SeqNum etc having to match)
$updatedPatternStart = "SeqNum=`""
$updatedPatternEnd = "`""
$r = [regex] $pattern
$currentSequenceNumber = 1
$filePrefix = Get-Random -Minimum 1 -Maximum 999999
$filePrefix
$outFile = "c:\temp\bsa_$filePrefix.xml"
$outFile
$inFile | ForEach-Object {
$currentLine = $_
$result = $r.Match($currentLine)
if ($result.Success) {
$foundLiteral = $result.Value
# So $result.Value now becomes the literal string we want to replace
"Found a pattern match: $foundLiteral"
$replacementString = Set-ReplacementString $updatedPatternStart $currentSequenceNumber $updatedPatternEnd
$updatedLine = $currentLine -replace $foundLiteral, $replacementString
$updatedLine
$currentSequenceNumber++
$updatedLine | Out-File -FilePath $outFile -Append
} else {
$currentLine | Out-File -FilePath $outFile -Append
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment