Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamically add parameters to Powershell cmdlet

BACKGROUND
I have the cmdlet Send-MailMessage, it uses a dynamically generated HTML file as the body and an XML file for all other config.

The XML file looks like this:

<root>
    ...
    <Emails>
        <Email id="statsEmail" SMTPSvr="[email protected]">
            <config>
                <from>[email protected]</from>
                <to>[email protected]</to>
                <to>[email protected]</to>
                <cc>[email protected]</cc>
                <bcc>[email protected]</bcc>
                <subject>Statistics</subject>
            </config>
        </Email>
        ...
    </Emails>
</root>

And if I invoke it with Powershell like this: $config = $configXML.selectNodes("//Email[@id="statsEmail"]")

Send-MailMessage -SmtpServer $config.SMTPSvr `
    -From $config.From `
    -To $config.To -Cc $config.Cc -Bcc $config.Bcc `
    -Subject $config.Subject `
    -Attachments $attachArray `
    -BodyAsHtml "$SCRIPT:htmlBody"

It works just fine..

ISSUE
If the manager then decides he no longer wants to be BCCed in, I just remove the BCC element from the config file right? WRONG, Powershell (quite rightly) throws an error because I’m specifying the BCC param and $config.bcc is about as $null as it gets.

Here's the error (just incase someone asks):

Send-MailMessage : Cannot validate argument on parameter 'Cc'. The argument is null or empty. Supply an argument that is not null or empty and then try the command again.
+ CategoryInfo : InvalidData: (:) [Send-MailMessage], ParameterBindingValidationException

CONCLUDE
I realise I could solve this by putting Send-MailMessage in a nested if, I'm just curious if there's a cleaner solution to add/remove the Cc & Bcc params dynamically.

like image 281
AndyMeFul Avatar asked Aug 12 '13 12:08

AndyMeFul


Video Answer


1 Answers

Create a hashtable with all of the parameters and values that you want to send to the cmdlet, and then "splat" it. This will give you programmatic control over the parameters and values that get sent in, and display them in an easy-to-read (for humans) format, like in the following example:

# Define the parameters and values to give to Send-MailMessage.
$parameters = @{
    From = $config.From
    ...
    To   = $config.To
}

# Check if $config.BCC is null. If it isn't, add it to the hashtable.
if ($null -ne $config.Bcc) {
    $parameters.Add("BCC", $config.Bcc)
}

# Call Send-MailMessage with all of our prepared parameters.
Send-MailMessage @parameters
like image 67
mikekol Avatar answered Oct 10 '22 18:10

mikekol