Monday, May 9, 2011

Logging Azure startup tasks

This is one of the old DOS batch file tricks.  Really simple, really useful, and still works after 20+ years.

When you need to send the output of a script to a file:

>> pathToMyLog\Mylog.log

IN the case of Azure startup tasks and you want a quick way to see what happened, what is happening simply define this in the startup task.

image

<Startup>
  <Task commandLine="DSInstall\InstallDS.cmd >> %Public%\Documents\StartupTask.log" executionContext="elevated" />
</Startup>

The important thin got remember is that this will always append a previous file.  So if the script runs multiple times, you will have the entries repeat.  And this is also useful.

Most developers I would with would simply be looking at me and say:  Just turn on Intellitrace, support is right there.  Well, that is fine – I will let them do that.  But yet, I bet they find this useful.  Winking smile

There is also the final end tag of “2>>&1” that can be used to be sure that error messages are logged (as the “>>” takes all of the console output and logs it to file).

Thursday, May 5, 2011

PowerShell and XML–bah to overly simplistic examples

Okay, I have been manipulating XML with PowerShell on and off for over a year now.  And I will tell you, all the examples that you find on the internet are way too simplistic.

I have yet to get a piece of XML out of code that is very simple, neat and tidy.

Working with CIM interfaces and XML application configuration files I frequently find my XML muddied up with array strings within tags.

Oh my.  These arrays within an XML Element reek havoc on the nice simple XML parsing that PowerShell does (and assumes).

Or, worse yet, the XML is filled with namespaces and therefore you cannot simply [xml] (cast it to XML) and deal with it.

Say for example that I have a web config file that I want to change, and it is written in XML.  first I have to get the file:

$file = get-childitem -path "IIS:\Sites\Default Web Site\App\Settings\web.config"

Then get the content of the config file and cast it to XML:

$xml = [xml](get-content $file)

Within this file are tags and settings that are actually arrays of settings within tags.  Or they are dictionaries (but they don’t return that way).

In the XML might look like this:

<AppThings allowSomething="on" showBar="off">
  <client />
  <someAppPolicy setting="off" />
  <someOtherAppPolicy enableFoo="off" />
</AppThings>
 

To modify one of these array settings I simply treat it as an array an modify the proper setting.

$somePolicy = @($xml.GetElementsByTagName("someAppPolicy"))

foreach ($e in $somePolicy) {
    if ($e.setting -eq "off" ) {
    $e.setting = "on"
    }
}

At the end you just have to remember to write the XML back to the file:

$xml.Save($file.FullName)