Thursday 18 February 2010

Using XmlPeek and XmlPoke in PowerShell

<xmlpeek /> and <xmlpoke /> commands in NAnt are really useful when it comes to changing configuration files during your automated build process. But do we do when we need that functionality in PowerShell? I did not find any native implementation but it's really easy to implement your own. Here it goes:

function xmlPeek($filePath, $xpath) {
    [xml] $fileXml = Get-Content $filePath
    return $fileXml.SelectSingleNode($xpath).Value
}

function xmlPoke($file, $xpath, $value) {
    $filePath = $file.FullName

    [xml] $fileXml = Get-Content $filePath
    $node = $fileXml.SelectSingleNode($xpath)
    if ($node) {
        $node.Value = $value

        $fileXml.Save($filePath) 
    }
}

It accepts FileInfos so it can be easily used together with Get-ChildItem:

Get-ChildItem P:\MyProject -Include *.config -Recurse | %{ xmlPoke($_, "/configuration/connectionStrings/add[@name='MainConnectionString']/@connectionString", "DataSource=MyDB") }

Enjoy! :)

1 comment: