简体   繁体   English

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

[英]Powershell script does not run via Scheduled Tasks

I have a small script on my Domain Controller that is setup to email me via SMTP about the latest Security Event 4740.我的域控制器上有一个小脚本,该脚本设置为通过 SMTP 向我发送有关最新安全事件 4740 的电子邮件。

The script, when executed manually, will run as intended;手动执行时,脚本将按预期运行; however, when setup to run via Scheduled Tasks, and although it shows to have been executed, nothing happens (no email).但是,当设置为通过计划任务运行时,尽管它显示已执行,但没有任何反应(没有电子邮件)。

The script is as follows:脚本如下:

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)

Scheduled Task is setup as follows:计划任务设置如下:

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

I have also tried the following:我还尝试了以下方法:

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

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

According to the Tasks History: Task Started, Action Started, Created Task Process, Action Completed, Task Completed.根据任务历史记录:任务已启动、操作已启动、已创建任务流程、操作已完成、任务已完成。 I have looked through some various links on the site with the same 'issue' but they all seem to have some sort of variable that I do not have.我浏览了网站上具有相同“问题”的一些不同链接,但它们似乎都有某种我没有的变量。 I have also tried some of the mentioned solutions thinking they may be somewhat related, but alas nothing is working.我也尝试了一些提到的解决方案,认为它们可能有些相关,但是没有任何效果。 I have even tried removing my Scheduled Task and resetting it as mentioned here: http://blogs.technet.com/b/heyscriptingguy/archive/2012/08/11/weekend-scripter-use-the-windows-task-scheduler-to-run-a-windows-powershell-script.aspx我什至尝试删除我的计划任务并按照此处所述重置它: http : //blogs.technet.com/b/heyscriptingguy/archive/2012/08/11/weekend-scripter-use-the-windows-task-scheduler -to-run-a-windows-powershell-script.aspx

Has anyone run into this type of error before or know how to bypass this issue?有没有人遇到过这种类型的错误或知道如何绕过这个问题?

Troubleshooting:故障排除:

I decided to try an call a .bat file via a scheduled task.我决定尝试通过计划任务调用 .bat 文件。 I created a simple file that would echo the current date/time to a monitored folder.我创建了一个简单的文件,它将当前日期/时间回显到一个受监控的文件夹。 Running the file manually and via a task triggered by the 4740 Event achieved desired results.手动和通过 4740 事件触发的任务运行文件达到了预期的结果。 Changing the .bat file to instead call the .ps1 file worked manually.将 .bat 文件更改为手动调用 .ps1 文件。 When triggered by the 4740 Event, now the .bat will no longer run.当由 4740 事件触发时,现在 .bat 将不再运行。

Change your Action to:将您的操作更改为:

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

On a Windows 2008 server R2: In Task Scheduler under the General Tab - Make sure the 'Run As' user is set to an account with the right permissions it takes to execute the script.在 Windows 2008 服务器 R2 上:在常规选项卡下的任务计划程序中 - 确保将“运行身份”用户设置为具有执行脚本所需的正确权限的帐户。

Also, I believe you have the "Run only when user is logged on" Option checked off.另外,我相信您已选中“仅在用户登录时运行”选项。 Change that to "Run whether user is logged on or not".将其更改为“无论用户是否登录都运行”。 Leave the Do Not Store password option unchecked, and you'll probably need the "Run with Highest Privileges" option marked.不选中“不存储密码”选项,您可能需要标记“以最高权限运行”选项。

Although you may have already found a resolution to your issue, I'm still going to post this note to benefit someone else.尽管您可能已经找到了问题的解决方案,但我仍将发布此说明以让其他人受益。 I ran into a similar issue.我遇到了类似的问题。 I basically used a different domain account to test and compare.我基本上使用不同的域帐户进行测试和比较。 The task ran just fine with "Run whether user is logged on or not" checked.该任务运行得很好,选中了“无论用户是否登录都运行”。

A couple of things to keep in mind and make sure of:要记住并确保以下几点:

  1. The account being use to execute task must have "Logon as batch job" rights under the local security policy of the server (or be member of local Admin group).用于执行任务的帐户必须具有服务器本地安全策略下的“作为批处理作业登录”权限(或者是本地管理员组的成员)。 You must specified the account you need to run scripts/bat files.您必须指定运行脚本/bat 文件所需的帐户。
  2. Make sure you are entering the correct password characters确保输入正确的密码字符
  3. Tasks in 2008 R2 don't run interactively specially if you run them as "Run whether user is logged on or not".如果您将 2008 R2 中的任务作为“无论用户是否登录都运行”来运行它们,则它们不会专门以交互方式运行。 This will likely fail specially if on the script you are looking for any objects\\resource specific to a user-profile when the task was created as the powershell session will need that info to start, otherwise it will start and immediately end.如果在创建任务时在脚本上查找特定于用户配置文件的任何对象\\资源,这可能会特别失败,因为 powershell 会话将需要该信息才能启动,否则它将启动并立即结束。 As an example for defining $Path when running script as "Run whether user is logged on or not" and I specify a mapped drive.作为在运行脚本时将 $Path 定义为“无论用户是否登录都运行”的示例,我指定了一个映射驱动器。 It would look for that drive when the task kicks off, but since the user account validated to run task is not logged in and on the script you are referring back to a source\\object that it needs to work against it is not present task will just terminate.它会在任务开始时查找该驱动器,但由于验证为运行任务的用户帐户未登录,并且在脚本上,您正在引用它需要对其进行处理的源\\对象不存在任务将只是终止。 mapped drive (\\server\\share) x:\\ vs. Actual UNC path \\server\\share映射驱动器 (\\server\\share) x:\\ 与实际 UNC 路径 \\server\\share
  4. Review your steps, script, arguments.查看您的步骤、脚本、参数。 Sometimes the smallest piece can make a big difference even if you have done this process many times.有时,即使您已经多次执行此过程,最小的部分也可以产生很大的不同。 I have missed several times a character when entering the password or a semi-colon sometimes when building script or task.在构建脚本或任务时,有时我在输入密码或分号时错过了几次字符。

Check this link and hopefully you or someone else can benefit from this info: https://technet.microsoft.com/en-us/library/cc722152.aspx检查此链接,希望您或其他人可以从此信息中受益: https : //technet.microsoft.com/en-us/library/cc722152.aspx

NOTE : Please ensure that you select Create a Basic task Action and NOT the Create Task Action.注意:请确保您选择创建基本任务操作而不是创建任务操作。

I found the following solution:我找到了以下解决方案:

1) Make powershell.exe run as administrator for this 1)为此使powershell.exe以管理员身份运行

  1. right-click on the powershell.exe icon右键单击powershell.exe图标
  2. click on properties under the shortcut key menu点击快捷键菜单下的属性
  3. click on the advance button;点击前进按钮; check that "run as administrator" is checked.检查“以管理员身份运行”是否已选中。

2) in the task scheduler window under the action pane add the following script as a new command 2) 在任务计划程序窗口的操作窗格下添加以下脚本作为新命令

%SystemRoot%\syswow64\WindowsPowerShell\v1.0\powershell.exe -NoLogo -NonInteractive -ExecutionPolicy Bypass -noexit -File "C:\ps1\BackUp.ps1"

在此处输入图片说明

To achieve "Run as Administrator" functionality I implemented the flag:为了实现“以管理员身份运行”功能,我实现了以下标志:

-ExecutionPolicy Bypass

Which only seems to take effect when executing Powershell files.这似乎只在执行 Powershell 文件时生效。 So I dropped my command into .ps1 file, run it with -ExecutionPolicy Bypass, and now my scheduled task is behaving as expected.所以我把我的命令放到 .ps1 文件中,用 -ExecutionPolicy Bypass 运行它,现在我的计划任务按预期运行。

Program: Powershell.exe
Add Arguments: -ExecutionPolicy Bypass -File C:\pscommandFile.ps1

Good morning,早上好,

I know this is an old thread but I just ran across it while looking for a similar problem - script was running successfully but not doing its work.我知道这是一个旧线程,但我只是在寻找类似问题时遇到了它 - 脚本运行成功但没有完成它的工作。 I can't find the post that helped me but my issue was that I was running the script as the domain admin.我找不到对我有帮助的帖子,但我的问题是我以域管理员身份运行脚本。 When I followed the suggestion of the post and added the domain admin to the local administrator's group it worked.当我按照帖子的建议将域管理员添加到本地管理员组时,它起作用了。 I hope this helps others with the same issue I had.我希望这可以帮助其他与我遇到相同问题的人。

Joe

If you don't have any error messages and don't know what the problem is - why PowerShell scripts don't want to start from a Scheduled Task do the following steps to get the answer:如果您没有任何错误消息并且不知道问题出在哪里 - 为什么 PowerShell 脚本不想从计划任务启动,请执行以下步骤以获得答案:

  1. Run CMD as a user who has been set for Scheduled Task to execute the PowerShell script以已设置定时任务的用户身份运行CMD执行PowerShell脚本
  2. Browse to the folder where the PowerShell script is located浏览到 PowerShell 脚本所在的文件夹
  3. Execute the PowerShell script (remove all statements that block the error notifications if any exists inside of the script like $ErrorActionPreference= 'silentlycontinue')执行 PowerShell 脚本(如果脚本中存在任何阻止错误通知的语句,如 $ErrorActionPreference= 'silentlycontinue',则删除所有语句)

You should be able to see all error notifications.您应该能够看到所有错误通知。

In case of one of my script it was:如果我的脚本之一是:

"Unable to find type [System.ServiceProcess.ServiceController]. Make sure that the assembly that contains this type is loaded." “无法找到类型 [System.ServiceProcess.ServiceController]。确保加载了包含此类型的程序集。”

And in this case I have to add additional line at the begining of the script to load the missing assembly:在这种情况下,我必须在脚本的开头添加额外的行来加载缺少的程序集:

Add-Type -AssemblyName "System.ServiceProcess"添加类型 -AssemblyName "System.ServiceProcess"

And next errors:和下一个错误:

Exception calling "GetServices" with "1" argument(s): "Cannot open Service Control Manager on computer ''. This operation might require other privileges."使用“1”个参数调用“GetServices”时出现异常:“无法打开计算机“上的服务控制管理器”。此操作可能需要其他权限。

select : The property cannot be processed because the property "Database Name" already exists select : 无法处理该属性,因为属性“数据库名称”已存在

Found successful workaround that is applicable for my scenario:找到了适用于我的场景的成功解决方法:

Don't log off, just lock the session!不要注销,只需锁定会话!

Since this script is running on a Domain Controller, I am logging in to the server via the Remote Desktop console and then log off of the server to terminate my session.由于此脚本在域控制器上运行,因此我通过远程桌面控制台登录到服务器,然后从服务器注销以终止我的会话。 When setting up the Task in the Task Scheduler, I was using user accounts and local services that did not have access to run in an offline mode, or logon strictly to run a script.在任务计划程序中设置任务时,我使用的用户帐户和本地服务无权在离线模式下运行,或严格登录以运行脚本。

Thanks to some troubleshooting assistance from Cole, I got to thinking about the RunAs function and decided to try and work around the non-functioning logons.感谢 Cole 提供的一些故障排除帮助,我开始考虑 RunAs 功能并决定尝试解决无法运行的登录问题。

Starting in the Task Scheduler, I deleted my manually created Tasks.从任务计划程序开始,我删除了手动创建的任务。 Using the new function in Server 2008 R2, I navigated to a 4740 Security Event in the Event Viewer, and used the right-click > Attach Task to this Event... and followed the prompts, pointing to my script on the Action page.使用 Server 2008 R2 中的新功能,我导航到事件查看器中的 4740 安全事件,并使用右键单击 > 将任务附加到此事件...并按照提示操作,在操作页面上指向我的脚本。 After the Task was created, I locked my session and terminated my Remote Desktop Console connection.创建任务后,我锁定了会话并终止了远程桌面控制台连接。 WIth the profile 'Locked' and not logged off, everything works like it should.在配置文件“锁定”且未注销的情况下,一切正常。

In addition to advices from above I was getting error and found solution on following link http://blog.vanmeeuwen-online.nl/2012/12/error-value-2147942523-on-scheduled.html .除了上面的建议之外,我还遇到了错误,并在以下链接http://blog.vanmeeuwen-online.nl/2012/12/error-value-2147942523-on-scheduled.html上找到了解决方案。

Also this can help:这也可以帮助:

In task scheduler, click on the scheduled job properties, then settings.在任务计划程序中,单击计划的作业属性,然后单击设置。

In the last listed option: "if the task is already running, the following rule applies:" Select "stop the existing instance" from the drop down list.在最后列出的选项中:“如果任务已经在运行,则适用以下规则:”从下拉列表中选择“停止现有实例”。

I think the answer to this is relevant too:我认为这个答案也很重要:

Why is my Scheduled Task updating its 'Last Run Time' correctly, and giving a 'Last Run Result' of '(0x0)', but still not actually working?为什么我的计划任务正确更新了它的“上次运行时间”,并给出了“(0x0)”的“上次运行结果”,但仍然没有实际工作?

Summary: Windows 2012 Scheduled Tasks do not see the correct environment variables, including PATH , for the account which the task is set to run as.摘要: Windows 2012 计划任务没有看到正确的环境变量,包括PATH ,对于任务设置为运行的帐户。 But you can test for this, and if it is happening, and once you understand what is happening, you can work around it.但是您可以对此进行测试,如果它正在发生,一旦您了解正在发生的事情,您就可以解决它。

One more idea that worked.另一个有效的想法。 It's really silly, but, apparently, the default target OS setting (bottom right corner of the screen) is Vista / Windows Server 2008 .这真的很愚蠢,但显然,默认的目标操作系统设置(屏幕右下角)是Vista / Windows Server 2008 As we're past the 10 year mark, it is likely that your Powershell script will not be compatible to these.由于我们已经过了 10 年,您的 Powershell 脚本很可能与这些不兼容。

Changing the target to Windows Server 2016, as shown on the screenshot below, did the trick for me.将目标更改为 Windows Server 2016,如下面的屏幕截图所示,对我有用。

更改屏幕截图上的设置

I was having almost the same problem as this but slightly different on Server 2012 R2.我遇到了与此几乎相同的问题,但在 Server 2012 R2 上略有不同。 I have a powershell script in Task Scheduler that copies 3 files from one location to another.我在任务计划程序中有一个 powershell 脚本,可以将 3 个文件从一个位置复制到另一个位置。 If I run the script manually from powershell, it works like a charm.如果我从 powershell 手动运行脚本,它就像一个魅力。 But when run from Task Scheduler, it only copies the first 2 small files, then hang on the 3rd (large file).但是从Task Scheduler运行时,它只复制前2个小文件,然后挂在第3个(大文件)上。 And I was also getting a result of "The operator or administrator has refused the request".而且我也得到了“操作员或管理员拒绝了请求”的结果。 And I have done almost everything in this forum.我在这个论坛上做了几乎所有的事情。

Here is the scenario and how I fixed it for me.这是场景以及我如何为我修复它。 May not work for others, but just in case it will:可能对其他人不起作用,但以防万一:

Scenario: 1. Powershell script in Task Scheduler 2. Ran using a domain account which is a local admin on the server 3. Selected 'Run whether user is logged on or not" 4. Run with highest priviledges场景:1. 任务计划程序中的 Powershell 脚本 2. 使用域帐户运行,该帐户是服务器上的本地管理员 3. 选择“无论用户是否登录都运行” 4. 以最高权限运行

Fix: 1. I had to login to the server using the domain account so that it created a local profile in C:\\Users.修复: 1. 我必须使用域帐户登录到服务器,以便它在 C:\\Users 中创建本地配置文件。 2. Checked and made user that the user has access to all the drives I referred to on my script 2. 检查并让用户访问我在脚本中提到的所有驱动器

I believe #1 is the main fix for me.我相信 #1 对我来说是主要的修复方法。 I hope this works for others out there.我希望这对其他人有用。

请确保Cole9350提到的参数是小写的

If youu are having this problem under WIN 10 this might solve your problem as it did for me.如果您在 WIN 10 下遇到此问题,这可能会像对我一样解决您的问题。 An update messed up the task scheduler.更新搞砸了任务调度程序。

http://answers.microsoft.com/en-us/windows/forum/windows_10-performance/anniversary-update-version-1607-build14393-breaks/d034ab52-5d49-4b92-976a-a1355b5a6e6d?page=2 http://answers.microsoft.com/en-us/windows/forum/windows_10-performance/anniversary-update-version-1607-build14393-breaks/d034ab52-5d49-4b92-976a-a1355b5a6e6d?page=2

This comment solved my problem.这个评论解决了我的问题。

Your tip about "one-time" tasks works great - it will definitely be sufficient as a workaround until MS fixes the issue.您关于“一次性”任务的提示效果很好 - 在 MS 解决问题之前,它绝对足以作为一种解决方法。 The only advantage to "daily" as far as I can see is that lack of the arbitrary date associated with the run time.据我所知,“每天”的唯一优势是缺少与运行时间相关的任意日期。 It might be confusing to others as to why the job is set to start on X date.其他人可能会混淆为什么将作业设置为在 X 日期开始。

Trigger settings "Einmal" means "one-time", "Sofort" means "At once"触发设置“Einmal”的意思是“一次性”,“Sofort”的意思是“一次”

In my case (the same problem) helped to add -NoProfile in task action command arguments and check checkbox "Run with highest privileges", because on my server UAC is on (active).在我的情况下(同样的问题)有助于在任务操作命令参数中添加 -NoProfile 并选中复选框“以最高权限运行”,因为在我的服务器上 UAC 已打开(活动)。

More info about it enter link description here关于它的更多信息在此处输入链接描述

I have another solution for this problem that might apply to some of you.对于这个问题,我有另一种解决方案,可能适用于你们中的一些人。

After I created my power shell (xyz.ps1) script, I opened it in notepad for subsequent editing.在我创建了我的 power shell (xyz.ps1) 脚本之后,我在记事本中打开它以进行后续编辑。 Hence Windows made an association between my xyz.ps1 file with notepad.exe and Scheduler was trying to run my power shell script (xyz.ps1) with notepad.exe in the background instead of executing it in Powershell.因此,Windows 在我的 xyz.ps1 文件与 notepad.exe 之间建立了关联,并且调度程序试图在后台使用 notepad.exe 运行我的 power shell 脚本(xyz.ps1),而不是在 Powershell 中执行它。 I found this problem by paying close attention to "Display all running tasks" section in the scheduler, which showed that notepad.exe was being used to run the xyz.ps1 script.我通过密切关注调度程序中的“显示所有正在运行的任务”部分发现了这个问题,这表明 notepad.exe 被用于运行 xyz.ps1 脚本。 To verify this, I right clicked on my xyz.ps1 file in windows explorer, went to "Properties", and it showed Notepad against the "Opens With" section.为了验证这一点,我在 Windows 资源管理器中右键单击我的 xyz.ps1 文件,转到“属性”,并在“打开方式”部分显示记事本。 Then I changed the "Opens With" to %SystemRoot%\\SysWOW64\\WindowsPowerShell\\v1.0\\powershell.exe.然后我将“打开方式”更改为 %SystemRoot%\\SysWOW64\\WindowsPowerShell\\v1.0\\powershell.exe。 This did the trick.这成功了。 Now the scheduler would execute my xyz.ps1 using powershell.exe and gave me the desired results.现在调度程序将使用 powershell.exe 执行我的 xyz.ps1 并给我所需的结果。

To locate your powershell.exe, refer to this article: https://www.powershelladmin.com/wiki/PowerShell_Executables_File_System_Locations要找到您的 powershell.exe,请参阅这篇文章: https : //www.powershelladmin.com/wiki/PowerShell_Executables_File_System_Locations

I had very similar issue, i was keeping the VSC window with powershell script all the time when running the schedule task manually.我有非常相似的问题,我在手动运行计划任务时一直使用 powershell 脚本保留 VSC 窗口。 Just closed it and it started working as expected.刚刚关闭它,它开始按预期工作。

I had the same issue, while running the couple of scripts.我在运行几个脚本时遇到了同样的问题。 When i execute it manually from task scheduler, The script was executing flawlessly.当我从任务调度程序手动执行它时,脚本运行完美。 But it was not executing at the scheduled time automatically.但它没有在预定的时间自动执行。

The following resolution worked for me以下决议对我有用

Find the location of the powershell exe , Right click and go to security options,Add the "Authenticated users" to the group or user names and give full control.找到powershell exe的位置,右键单击并转到安全选项,将“经过身份验证的用户”添加到组或用户名中并给予完全控制。

Once this is done wait for the script to executed.完成后等待脚本执行。

In my case it was related to a .ps1 referral inside the ps1 script which was not signed (you need to unblock it at the file properties) , also I added as first line:在我的情况下,它与未签名的 ps1 脚本中的 .ps1 引用有关(您需要在文件属性中取消阻止它),我也添加为第一行:

Set-ExecutionPolicy -ExecutionPolicy Unrestricted -Force Set-ExecutionPolicy -ExecutionPolicy Unrestricted -Force

Then it worked然后它起作用了

我对这个问题的修复是确保我使用了 ps1 文件中所有文件名的完整路径。

I had a similar problem where only half the script would run using task scheduler, but would run fine under the same account running the script manually.我有一个类似的问题,其中只有一半的脚本可以使用任务调度程序运行,但在手动运行脚本的同一帐户下可以正常运行。 The problem was I was referencing my own module.问题是我正在引用我自己的模块。 When I added the functions directly to my script file, the task scheduler worked, but when I used the module task scheduler failed.当我将函数直接添加到我的脚本文件中时,任务调度程序工作,但是当我使用模块任务调度程序时失败。 The same coded (module) running under the same account worked fine without task scheduler.在相同帐户下运行的相同编码(模块)在没有任务调度程序的情况下运行良好。

I think this was some type of issue with how windows handles environment variables doing a run as.我认为这是 Windows 如何处理运行时环境变量的某种类型的问题。 When I referenced the module via the full path (instead of module name) it worked from task scheduler.当我通过完整路径(而不是模块名称)引用模块时,它从任务调度程序工作。

after trying a lot of time...在尝试了很多时间之后......

task scheduler : powershell.exe -noexit & .\\your_script.ps1任务调度程序:powershell.exe -noexit & .\\your_script.ps1

be sure to put your script in this folder : windows\\system32一定要把你的脚本放在这个文件夹中:windows\\system32

good luck !祝你好运!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM