Edit appSettings using PowerShell

Disclaimer: I am not a powershell expert and this script could do anything from update your appSettings to wipe your hard drive. You have been warned! :-)

Today I had to write a quick powershell script that would be used just after we deployed our application to the UAT environment. Basically we needed a quick way to update a few settings inside the applications configuration file for demonstration purposes to prove a concept to our client.

$configuration = "C:\App\app.config"

[xml]$xml = New-Object XML
$xml.Load($configuration)

foreach($n in $xml.selectnodes("/configuration/appSettings/add"))
{
        switch($n.key)
        {
            "DeploymentDate" { $n.value = [DateTime]::Now.ToString("d/M/yyyy") }
            "DateOfInitialization" { $n.value = [DateTime]::Now.AddDays(-2).ToString("d/M/yyyy") }
        } 
}
$xml.Save($configuration)

Firstly we need to set the location of the configuration file and then load the Xml into an Xml Document. Using XPath I then navigated down the xml document to the appSettings child nodes.

Using a switch statement whist looping over the add nodes I could then set new values for any of the configuration settings based on the key.

<?xml version="1.0"?>
<configuration>
    <appSettings>
        <add key="DeploymentDate"  value="01/01/2010" />
        <add key="DateOfInitialization"  value="01/01/2010" />
    </appSettings>
</configuration>

Pretty simple! I now love powershell as its perfect for getting things like this done quickly and easily.

Twitter Twitter Twitter Twitter Twitter
June 11, 2010 19:00 by DanWatson

Extension Method From The Trenches – C# Week Of Year

Currently I am working in a slightly different capacity to what I am used to…. what I consider to be…. working in the trenches (basically getting involved in the day to day nitty gritty). Today I discovered there was no easy way to get the week number from a DateTime (I really expected there to be a WeekOfYear property on DateTime but there is not. Luckily it is a pretty easy to work this information out.

namespace DateTimeWeekYearExample
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine(new DateTime(2010, 01, 01).GetWeekNumber()); //Friday 01 January 2010 - Week 1
            Console.WriteLine(new DateTime(2010, 01, 03).GetWeekNumber()); //Sunday 03 January 2010 - Week 2
            Console.Read();

        }

    }

    public static class DateHelpers
    {
        public static int GetWeekNumber(this DateTime source)
        {
            return CultureInfo.CurrentCulture.Calendar.GetWeekOfYear(source, 
CalendarWeekRule.FirstDay,
DayOfWeek.Sunday); } } }

The great thing about the GetWeekOfYear method that hangs off of the culture information's calendar is that you can configure which day is the first day of the week as well as the calendar week rule.

Twitter Twitter Twitter Twitter Twitter
May 27, 2010 22:30 by DanWatson