Thursday, 30 October 2014

Dynamic Parameter and Value String Creation PowerShell

Whist working on a larger script with my colleague Rafael we found a need to build up a commands parameters on the fly before Invoking the command.  The reason is, we wished to only include the parameters and values which had been specified in our XML settings file.

We then created this handy function that along with some If Statements we could manipulate the string how we needed.

The function will also handle $True and $False values, if by some chance you need this to be True and False instead you may need to tweek the function.

Raf also amended the function to include an option for ignoring "SpeachMarks" just in the event you needed it to :)

At the end all you would need to do to run your command would be something like this:
Invoke-Expression $ADRCommand

The Function is as follows:
$Global:ADRCommand = "New-CMSoftwareUpdateAutoDeploymentRule"
Function Add-ToString([string]$parameter, [string]$value,[boolean]$IgnoreSpeechMarks)
{
if ($value -eq "True")
{$Value = '$True'
$Global:ADRCommand += " " + $parameter + " " + $Value
}
elseif ($value -eq "False"){$Value = '$False'
$Global:ADRCommand += " " + $parameter + " " + $Value
}
Else
{
if($IgnoreSpeechMarks = $True)
{
$Value = $Value -replace "'",""
$Global:ADRCommand += " " + $parameter + ' ' + $Value
}
else{$Global:ADRCommand += " " + $parameter + ' "' + $Value + '"'}
}
}

No comments:

Post a Comment

Blog Archive