Adding Multi-Line Parameter to Hashtable for Splatting

It mostly works for me. I am trying to add a parameter to my hash table before splatting. However, the parameter I'm trying to add is a set of two strings.

$myHT = @{
    From         = 'me@x.com'
    To           = 'them@x.com'
    SmtpServer   = 'mail.x.com'
}

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

Send-MailMessage @myHT

      

Of course powershell will treat this as three separate parameters, and errors accordingly. So to fix this, I tried something similar to:

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

      

The drive cannot be found. The drive named "C" does not exist.

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

      

This path format is not supported.

It seems to me that I am making a syntax error here, but cannot find any documentation on the correct path to do this.

Does anyone have any experience with this issue that they could share?

+3


source to share


2 answers


The method .Add()

only takes 2 arguments, and whatever you pass as the second argument will be assigned as-is.

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

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

      

Take a look (...)

around the PS array "$PSScriptRoot\x.pdf", "$PSScriptRoot\y.pdf"

to make sure it is recognized as such.



While usage is @(...)

also an option, it is usually unnecessary (and does unnecessary work behind the scenes).


Alternatively, using a keyed hash table access to add an item can make the assignment more readable:

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

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

      

+2


source


If you already know the array values ​​you want to use for Attachments

before initializing the hash table, you can use a simpler solution:



$myHT = @{
    From         = 'me@x.com'
    To           = 'them@x.com'
    SmtpServer   = 'mail.x.com'
    Attachments  = "$PSScriptRoot\x.pdf", "$PSScriptRoot\y.pdf"
}

Send-MailMessage @myHT

      

+1


source







All Articles