Streamlining PowerShell Scripts and Configurations

by Doug Finke on December 24, 2013

in Microsoft,PowerShell,Scripting Games,Xml

I write a lot of PowerShell and I see a lot of PowerShell (I dream using Invoke-Command for remote places).

Tanner Ladd posted this “Automated PDF Email Distribution of Tableau Views Using PowerShell and Tabcmd” and is worth reading.

Here is an alternative to how he uses the XML for configuration.

When in PowerShell do as PowerShell

XML is fine for holding configuration, but when in PowerShell, do as PowerShell.

First, I’d like to dial in on how Tanner could have simplified working with his configuration. Here is a snippet.

    <!--This is the absolute path of the logfile-->
    <!--This is the .csv file containing our email address and filter options-->
        <!--This is the server that we are downloading the files from-->
        <!--This is the tableau server user name and password-->
        <!--This is the URL of the tableau view we want.-->
        <!--It is also possible to pull the file as .csv or .png -->
        <!--The .ps1 script will append the file with the filter-->

Here’s the PowerShell he uses to get the values for logfile and csvfile.

[xml]$config_xml = Get-Content $config_path            
$logfilepath = `
$csvpath     = `

Perfectly valid but that’s a lot of code. It can be simplified.

[xml]$config_xml = Get-Content $config_path            
$logfilepath = $config_xml.logfile            
$csvpath     = $config_xml.csvfile

No need to get XPath involved. Plus, less script for you to maintain and read later. Let PowerShell do the magic for you.

PowerShell Kicks Simplicity Up A Notch

Using a PowerShell hash table (associative array) has benefits.

  • First, it’s PowerShell
  • You can save this in a ps1 file and dot source it, which does syntax checking
  • You can use PowerShell code to add to the configuration on the fly

To my taste, this is more readable.

$configuration = @{            
    #This is the absolute path of the logfile            
            subject='Awesome Tableau Report Delivery'            
            body='I get a raise now, right??'            

Now you can dot source the PowerShell file and easily read, update and add to the configuration as you go.

. .\config.ps1            
# add a key            
# more PowerShell here            

PowerShell Scripting Games 2014

Head on over and register for the upcoming games. There’ll be lots of great challenges and it’s a terrific place to learn PowerShell techniques that’ll help you master the language and help you get your job done faster and better.

{ 0 comments… add one now }

Leave a Comment

You can use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Previous post:

Next post:

You are forbidden!