Using external parameters in ScriptBlock when sending mail message in PowerShell script

0

Trying to send mail in the background, using start-job, but having a problem with passing parameters to the scriptblock.

Mail params define:

$mailParams=@{
    To = $AddressTo
    From = $AddressFrom
    Subject = $Subject
    Body = $Body
    SMTPServer = $SMTPServer
    #BodyAsHTML = $True
    #Port = 587
    #UseSSL = $True
    #Credential = $mailCred
}#End mailParams 

Sending mail command:

Send-MailMessage @mailparams

Expected:

start-job -scriptblock {Send-MailMessage @mailparams}

Tried to use start-job -scriptblock {Send-MailMessage} -ArgumentList $mailparams, but same problem, all params are null

Btw, open for any better suggestion how to execute it in the background

igor

Posted 2018-08-14T10:54:14.050

Reputation: 253

Answers

2

you need to have a param() inside your Scriptblock to receive the Parameters you're sending in ArgumentList

$MailParams = @{
    To = $AddressTo
    From = $AddressFrom
    Subject = $Subject
    Body = $Body
    SMTPServer = $SMTPServer
    #BodyAsHTML = $True
    #Port = 587
    #UseSSL = $True
    #Credential = $mailCred
}

Start-Job { param($MailParams) ; Send-MailMessage @MailParams } -ArgumentList $MailParams

I always try to think about a scriptblock like a function. in a function you also need to pass and receive Arguments/Parameters. Same goes for Scriptblocks.

SimonS

Posted 2018-08-14T10:54:14.050

Reputation: 4 566

Thanks, works as expected. Yeah, didn't think that way – igor – 2018-08-14T12:07:04.780