Powershell Text File Processing

Today, I had a requirement to read a bunch of values from an xml file (web.config) and replace some place-holders in another file (asp inc file). I came up with (what I think is) a nice little solution to the problem.

First, I need to read the web.config file …

function readWebConfig
{
    param([string] $fileName)

    $encoding = detectEncoding $fileName
    $content = [IO.File]::ReadAllText($fileName, $encoding)
    $content
}

next I set up an array which I’ll use to process the file with …

function configureReplacements
{
    $list = @(
        ("CONNECTION_STRING", "//configuration/connectionStrings/add[@name='MyConnectionString']/@connectionString"),
        ("GOOGLE_MAPS_API_KEY", "//configuration/appSettings/add[@key='GoogleMapsApiKey']/@value")
    )
    $list
}

to make things a bit more flexible, this could easily be put into a simple text file.

then I process the file …

$replacements = configureReplacements
$webConfigContent = readWebConfig $webConfigFilename

$file = [IO.File]::ReadAllText($filename)
foreach ($replacement in $replacements)
{
    $text = $webConfigContent | Select-Xml $replacement[1]
    $file = $file.Replace('$' + $replacement[0] + '$', $text)
}
[IO.File]::WriteAllText($filename, $file)

I’ve used a convention of surrounding the replacement tags with $ signs

My asp inc file

<script language="VBScript" runat="Server">
    Const DATABASE_CONNECTION_STRING = "Provider=SQLOLEDB;$CONNECTION_STRING$"
    Const GOOGLE_MAPS_KEY = "$GOOGLE_MAPS_API_KEY$"
</script>

the relevant bits of my web.config file

<?xml version="1.0" encoding="utf-8"?>
    <configuration>
        <connectionstrings>
            <add name="MyConnectionString" connectionString="Data Source=(local);Initial Catalog=MyDatabase;Integrated Security=SSPI;" providerName="System.Data.SqlClient" />
        </connectionstrings>
        <appsettings>
            <add key="GoogleMapsApiKey" value="YOU_DIDNT_THINK_I_WOULD_GIVE_THAT_AWAY_DID_YOU_!!" />
        </appsettings>
    </configuration>

I put all of that into an AfterBuild target in my csproj file and it updates my asp inc file every time I build.

Resulting asp inc file

<script language="VBScript" runat="Server">
    Const DATABASE_CONNECTION_STRING = "Provider=SQLOLEDB;Data Source=(local);Initial Catalog=MyDatabase;Integrated Security=SSPI;"
    Const GOOGLE_MAPS_KEY = "YOU_DIDNT_THINK_I_WOULD_GIVE_THAT_AWAY_DID_YOU_!!"
</script>
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s