Jacob Colvin
Jacob Colvin

Reputation: 2835

Adding Multi-String Param to a Hashtable for Splatting

I have this mostly working. I am attempting to add a parameter to my hashtable before splatting. However, the parameter I am attempting to add is a collection of two strings.

$myHT = @{
    From         = '[email protected]'
    To           = '[email protected]'
    SmtpServer   = 'mail.x.com'
}

$myHT.Add("Attachments","$PSScriptRoot\x.pdf", "$PSScriptRoot\y.pdf")

Send-MailMessage @myHT

Of course powershell will treat this as being three separate parameters, and errors accordingly. So to rectify this, I have been trying things akin to:

$myHT.Add("Attachments","`"$PSScriptRoot\x.pdf`", `"$PSScriptRoot\y.pdf`"")

Cannot find drive. A drive with the name '"C' does not exist.

$myHT.Add("Attachments","$PSScriptRoot\x.pdf, $PSScriptRoot\y.pdf")

The given path's format is not supported.

I feel like I am making a syntax error here, but cannot find any documentation on the correct way to do this.

Does anyone have experience with this issue they could perhaps share?

Upvotes: 3

Views: 1090

Answers (2)

Mark Wragg
Mark Wragg

Reputation: 23355

If you already know the array values you want to use for Attachments prior to the hashtable being initialized you can use the simpler solution of:

$myHT = @{
    From         = '[email protected]'
    To           = '[email protected]'
    SmtpServer   = 'mail.x.com'
    Attachments  = "$PSScriptRoot\x.pdf", "$PSScriptRoot\y.pdf"
}

Send-MailMessage @myHT

Upvotes: 1

mklement0
mklement0

Reputation: 437513

The .Add() method takes only 2 arguments, and whatever you pass as the 2nd argument will be assigned as-is.

In your case, you want to assign an array, so you must pass that array as the single 2nd argument:

$myHT.Add("Attachments", ("$PSScriptRoot\x.pdf", "$PSScriptRoot\y.pdf"))

Note the (...) around PS array "$PSScriptRoot\x.pdf", "$PSScriptRoot\y.pdf" to ensure that it is recognized as such.

While using @(...) is also an option, it is generally unnecessary (and performs unnecessary work behind the scenes).


Alternatively, using key-based access to the hashtable to add an element may make the assignment more readable:

$myHT.Attachments = "$PSScriptRoot\x.pdf", "$PSScriptRoot\y.pdf"

# Equivalent
$myHT['Attachments'] = "$PSScriptRoot\x.pdf", "$PSScriptRoot\y.pdf"

Upvotes: 2

Related Questions