Converting Whitespace-Indented Output to XML
Example of taking output delimited by indents and trying to beat it into XML.
1 2 3 4 5 6 7 8 910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
|
function Get-HPSmartArrayConfigAsXML{ param ( [string]$HPSSACLIPath = 'C:\Program Files\HP\hpssacli\bin\hpssacli.exe', [string]$Path = "$home\Desktop\$env:ComputerName-hpssacli.xml" ) $ErrorActionPreference = 'Stop' # test-path or die!!! Get-Item $HPSSACLIPath | Out-Null $previousIndent = '' [System.Collections.ArrayList]$tagStack = @() [xml]$xml = '<xml></xml>' $nodeStackPointer = $xml.FirstChild $lastNodePointer = $xml.FirstChild & $HPSSACLIPath ctrl all show config | ? { $_ -replace '^\s+' -replace '\s+$' } | % { if ($_ -match '^(?<Indent>\s*)(?<Tag>\S+)\s+(?<Data>.*)') { $thisLineIndent = $Matches.Indent $tagName = $Matches.Tag $stringData = $Matches.Data -replace ' +', ' ' $node = $xml.CreateElement($tagName) $data = $xml.CreateElement('data') $node.AppendChild($data) $textNode = $xml.CreateTextNode($stringData) $data.AppendChild($textNode) if ($previousIndent.Length -eq $thisLineIndent.Length) { # no op } elseif ($previousIndent.Length -lt $thisLineIndent.Length) { Write-Verbose -Verbose "$($previousIndent.Length) -lt $($thisLineIndent.Length)" Write-Verbose -Verbose "`$nodeStackPointer = '$($nodeStackPointer.LocalName)'" Write-Verbose -Verbose "`$lastNodePointer = '$($lastNodePointer.LocalName)'" $nodeStackPointer = $lastNodePointer $previousIndent = $thisLineIndent } elseif ($previousIndent.Length -gt $thisLineIndent.Length) { Write-Verbose -Verbose "$($previousIndent.Length) -GT $($thisLineIndent.Length)" Write-Verbose -Verbose "`$nodeStackPointer = '$($nodeStackPointer.LocalName)'" Write-Verbose -Verbose "`$lastNodePointer = '$($lastNodePointer.LocalName)'" $nodeStackPointer = $nodeStackPointer.ParentNode $previousIndent = $thisLineIndent } $nodeStackPointer.AppendChild($node) $lastNodePointer = $node } else { Write-Warning "Failed to parse '$_'." } } | out-null $xml.Save($Path) Get-Item -Path $Path}
|