如果提供凭据参数,则在后台阻止发送MailMessage



我正试图使用以前通过Get-Credential检索并存储在$creds变量中的凭据在后台运行Send-MailMessage

以下命令几乎立即在后台被阻止:

Start-Job -ScriptBlock { Send-MailMessage -to "test@test.com" -from "test@test.com" -Subject "2342332" -Credential $creds }

运行Get-Job或将上一个命令分配给一个变量并显示它会给我以下状态:

Id     Name            PSJobTypeName   State         HasMoreData     Location             Command
--     ----            -------------   -----         -----------     --------             -------
25     Job25           BackgroundJob   Blocked       True            localhost             Send-MailMessage -to ...

直接运行完全相同的命令(没有Start-Job(将立即完成(在这种情况下,它将失败,因为我没有提供smtp服务器(。此外,在没有-Credential参数的情况下运行完全相同的命令将直接完成作业,也可以在后台运行(由于缺少smtp服务器的原因,它会失败,但这并不重要(。

有没有一种方法可以为该命令提供凭据,最好是使用Get-Credential,并能够使用Start-Job运行它?

后台作业在单独的子进程中运行,并且$creds不存在于所述单独的进程中。Send-MailMessage不接受$null-值作为-Credential的参数,因此会提示调用方输入有效的非null参数。

您可以在交互式shell中重现这种阻塞行为:

PS ~> Send-MailMessage -Credential:$null
PowerShell credential request
Enter your credentials.
User:

由于作业在没有交互功能的运行空间中运行,因此无法满足请求,作业状态被阻止。

-Credential $creds更改为-Credential $using:creds以强制powershell将$creds变量复制到作业的运行空间:

Start-Job -ScriptBlock { Send-MailMessage -to "test@test.com" -from "test@test.com" -Subject "2342332" -Credential $using:creds }

或者在调用Start-Job:时将其作为显式参数传递

Start-Job -ScriptBlock { Send-MailMessage -to "test@test.com" -from "test@test.com" -Subject "2342332" -Credential $args[0] } -ArgumentList $creds

最新更新