I’ve been doing a lot of configuration driven PowerShell scripts lately and I had a bit of trouble figuring this bit out so I thought I’d write up a short post about it. A lot of the cmdlets that I’ve been working with take in switch parameters and I needed a way to set those parameters dynamically based on settings in a configuration file. For those new or unfamiliar with PowerShell, switch parameters are just parameters that don’t have any corresponding value. Here’s an example:
Get-Command -Name Start-Sleep -Syntax
The “-Syntax” parameter above is a switch parameter – it takes no value and simply tells the Get-Command cmdlet to return only the syntax of the command. This particular cmdlet isn’t the best example of where you would want to set the parameters dynamically but you get the idea. So how would you set the -Syntax parameter dynamically? Here’s an example:
[xml]$config = Get-Content .\Configurations.xml Get-Command -Name Start-Sleep -Syntax:([bool]::Parse($config.Settings.ShowSyntax))
You can imagine an XML structure where there may be some kind of configuration settings (in this case: <Settings ShowSyntax="true" />). So you basically just add a colon (:) after the parameter and then provide a Boolean value; in this example because the value is in the form of an XmlElement we have to convert it to a Boolean.
This is one of those simple things that really pissed me off because it took forever for me to figure it out so I figured I'd share this simple tip with others (if you're a SharePoint person you'll want to know about all this stuff for the next version - believe me!).