Thursday, January 5, 2012

Did you know? – NuGetGallery Build (part 2)

To continue my previous post, let’s take a peek at Get-ConnectionString.ps1, because there is something in there that I had no idea you could do:
function Get-ConnectionString($configPath, $connectionStringName) 
{
  $config = [xml](get-content $configPath)
  
  $connectionString = ($config.configuration.connectionStrings.add | where { $_.name -eq $connectionStringName }).connectionString
  
  $connectionString = $connectionString.Replace("=", "%3D")
  $connectionString = $connectionString.Replace(";", "%3B")

  return $connectionString
}

Look at line #3, what’s up with that “[xml]” statement? Is it trying to cast the output of get-content as xml? That’s ok, I guess. But then the next line hits:
($config.configuration.connectionStrings.add | where { $_.name -eq $connectionStringName }).connectionString


It can traverse XML nodes and attributes like property objects?!? Kudos to you Mr. PowerShell. I have no idea how that [xml] works or what others are supported but I did a small experiment in the PowerShell REPL:
$foo = [xml] "<span></span>"
$foo.getType()

And it says that it is of type System.Xml.XmlDocument. The fact that you can traverse it and the way the author uses the where command-let to filter is awesome (was that you Drew? Kudos to you too man).

So now you know, maybe it will come handy some day.

2 comments:

  1. Yeah, that was me. I've said it many time, but I'll say it again: .NET dev'rs that aren't using Powershell (and I mean *really* using it) are missing out on a great tool.

    ReplyDelete
  2. Yeah, no kidding. Feels like productivity boost, to know it well.

    Take care.

    ReplyDelete