如果提供凭据参数,则 Send-MailMessage 在后台被阻止

Send-MailMessage blocked in background if supplied with credential argument

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

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

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 服务器)。此外,运行ning 不带 -Credential 参数的完全相同的命令将直接完成作业,以及 运行ning 在后台(由于相同的缺少 smtp 服务器原因,它将失败,但这并不重要)。

有没有办法为此命令提供凭据,最好使用 Get-Credential 并能够 运行 使用 Start-Job

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

您可以在交互式 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