Powershell CreateItem(0)在计划任务中失败

Powershell CreateItem(0)在计划任务中失败,powershell,scheduled-tasks,Powershell,Scheduled Tasks,我有PowerShell脚本发送电子邮件。当我直接运行它时,它工作得非常好 当我通过任务调度器计划它时,它失败了。下面是代码 # Get Outlook Object if (Get-Process Outlook) { $outlook = [System.Runtime.InteropServices.Marshal]::GetActiveObject('Outlook.Application') } else { $outlook = New-Object -ComObje

我有PowerShell脚本发送电子邮件。当我直接运行它时,它工作得非常好

当我通过任务调度器计划它时,它失败了。下面是代码

# Get Outlook Object
if (Get-Process Outlook) {
    $outlook = [System.Runtime.InteropServices.Marshal]::GetActiveObject('Outlook.Application')
} else {
    $outlook = New-Object -ComObject Outlook.Application
}

$Mail = $Outlook.CreateItem(0)
$Mail.To = "x@y.com"
$Mail.Subject = "Test Test TEst"
$Mail.Body = "Test Test TEst"
$Mail.Send()
$Outlook.CreateItem(0)
是失败的。 错误:

The term 'Outlook.CreateItem' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again. At C:\Temp\SendMail.PS1:9 char:31 + $Mail = Outlook.CreateItem <<<< (0) + CategoryInfo : ObjectNotFound: (Outlook.CreateItem:String) [], CommandNotFoundException + FullyQualifiedErrorId : CommandNotFoundException" 术语“Outlook.CreateItem”未被识别为cmdlet的名称, 函数、脚本文件或可操作程序。检查名字的拼写, 或者,如果包含路径,请验证路径是否正确,然后重试。 在C:\Temp\SendMail.PS1:9 char:31
+$Mail=Outlook.CreateItem我已将错误复制到OP。我猜您没有在正确的用户下运行它。请提供有关任务计划程序作业的信息(尤其是在哪个用户下运行该作业)。@tukan所说的内容+是否以最高权限(在计划任务设置中)运行该作业。对我来说,这非常有效,但前提是我在相同的上下文中运行(没有管理权限)@robdy,我已经测试过了。这没用。感谢您的回复,您是以“系统”方式运行任务,还是在未登录时允许它运行?如果我没记错的话,Outlook需要有一个“正确”的登录才能正常工作,所以如果您试图以系统的形式运行,或者没有登录,它将出错。尝试登录到计算机,将任务设置为以用户帐户的身份运行,并设置“仅在用户登录时运行”,然后查看您的运行情况。错误消息(格式正确后)清楚地表明,您的实际代码试图调用
Outlook.CreateItem
,而不是示例代码所声称的
$Outlook.CreateItem
。请不要发布您根据记忆捏造或键入的内容。创建一个演示您的问题的示例,并发布该代码以及从该代码中收到的错误。