I'm trying to run Send-MailMessage in background using credentials I have retrieved before via Get-Credential and stored in the $creds variable.
The following command will almost immediately be blocked in background:
Start-Job -ScriptBlock { Send-MailMessage -to "[email protected]" -from "[email protected]" -Subject "2342332" -Credential $creds }
Running Get-Job or assigning the previous command to a variable and displaying it will give me this status:
Id Name PSJobTypeName State HasMoreData Location Command
-- ---- ------------- ----- ----------- -------- -------
25 Job25 BackgroundJob Blocked True localhost Send-MailMessage -to ...
Running the exact same command directly (without Start-Job) will complete immediately (in this case it will fail as I haven't provided an smtp server). Also, running the exact same command without the -Credential argument will complete the job directly, as well as running in the background (it will fail for the same missing smtp server reason, but that's not important).
Is there a way to supply credentials to this command, preferably with Get-Credential and be able to run it with Start-Job?
CodePudding user response:
Background jobs are run in a separate child process, and $creds does not exist in said separate process. Send-MailMessage doesn't accept $null-values as arguments to -Credential, and therefore prompts the caller for a valid non-null argument.
You can reproduce this blocking behavior in an interactive shell:
PS ~> Send-MailMessage -Credential:$null
PowerShell credential request
Enter your credentials.
User:
Since the job is running in a runspace with no interactive capabilities, nothing can be done to satisfy the request and the job state is blocked.
Change -Credential $creds to -Credential $using:creds to force powershell to copy the $creds variable to the job's runspace:
Start-Job -ScriptBlock { Send-MailMessage -to "[email protected]" -from "[email protected]" -Subject "2342332" -Credential $using:creds }
Or pass it as an explicit argument when calling Start-Job:
Start-Job -ScriptBlock { Send-MailMessage -to "[email protected]" -from "[email protected]" -Subject "2342332" -Credential $args[0] } -ArgumentList $creds
