windows - Powershell 脚本不通过计划任务运行

标签 windows powershell scheduled-tasks

我的域 Controller 上有一个小脚本,该脚本设置为通过 SMTP 向我发送有关最新安全事件 4740 的电子邮件。

脚本在手动执行时将按预期运行;然而,当设置为通过计划任务运行时,尽管它显示已执行,但没有任何反应(没有电子邮件)。

脚本如下:

If (-NOT ([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator"))

{   
$arguments = "& '" + $myinvocation.mycommand.definition + "'"
Start-Process powershell -Verb runAs -ArgumentList $arguments
Break
}

$Event = Get-EventLog -LogName Security -InstanceId 4740 -Newest 5
$MailBody= $Event.Message + "`r`n`t" + $Event.TimeGenerated

$MailSubject= "Security Event 4740 - Detected"
$SmtpClient = New-Object system.net.mail.smtpClient
$SmtpClient.host = "smtp.domain.com"
$MailMessage = New-Object system.net.mail.mailmessage
$MailMessage.from = "fromemail@domain.com"
$MailMessage.To.add("toemail.domain.com")
$MailMessage.IsBodyHtml = 1
$MailMessage.Subject = $MailSubject
$MailMessage.Body = $MailBody
$SmtpClient.Send($MailMessage)

计划任务设置如下:

RunsAs:LOCAL SYSTEM

Trigger: On event - Log: Security, Event ID: 4740

Action:  Start Program - C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe

  Argument:  -executionpolicy bypass c:\path\event4740.ps1

我也试过以下方法:

Trigger: On event - Log: Security, Event ID: 4740

Action:  Start Program - C:\path\event4740.ps1

根据任务历史记录:任务开始、 Action 开始、创建任务流程、 Action 完成、任务完成。我浏览了网站上具有相同“问题”的各种链接,但它们似乎都有某种我没有的变量。我还尝试了一些提到的解决方案,认为它们可能有些相关,但可惜没有任何效果。我什至尝试删除我的计划任务并按照此处所述重置它:http://blogs.technet.com/b/heyscriptingguy/archive/2012/08/11/weekend-scripter-use-the-windows-task-scheduler-to-run-a-windows-powershell-script.aspx

有没有人遇到过这种类型的错误或者知道如何绕过这个问题?

故障排除:

我决定尝试通过计划任务调用 .bat 文件。我创建了一个简单的文件,它将当前日期/时间回显到受监控的文件夹中。手动运行文件并通过 4740 事件触发的任务实现预期结果。将 .bat 文件更改为手动调用 .ps1 文件。当由 4740 事件触发时,现在 .bat 将不再运行。

最佳答案

将您的操作更改为:

powershell -noprofile -executionpolicy bypass -file C:\path\event4740.ps1

在 Windows 2008 服务器 R2 上:在常规选项卡下的任务计划程序中 - 确保“运行方式”用户设置为具有执行脚本所需的正确权限的帐户。

此外,我相信您已选中“仅在用户登录时运行”选项。将其更改为“无论用户是否登录都运行”。不选中“不存储密码”选项,您可能需要标记“以最高权限运行”选项。

关于windows - Powershell 脚本不通过计划任务运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18259951/

相关文章:

powershell - 如何在 Sitecore Powershell Extensions 中获取通用链接字段属性

c# - 在 C# 中为 Powershell 2 构建模块,无需 Visual Studio 或访问 SDK

执行 Excel 互操作的 C# 控制台应用程序-按计划任务运行时失败-System.UnauthorizedAccessException

java - 通过 Java 访问 Windows 证书存储证书?

powershell - 如何在 Windows PowerShell 中比较两个 .zip 文件夹中的文件

C++ Pixel Grabber 错误的 RGB 值

java - 是什么导致 Spring 调度程序在应用程序和 servlet 启动之前执行?

java - ScheduledThreadPoolExecutor线程run方法执行final block 而不完成try block

java - java检测目录是否被修改

Python 脚本不适用于双击