Как запустить скрипт powershell в планировщике задач
Перейти к содержимому

Как запустить скрипт powershell в планировщике задач

  • автор:

 

Создание и управление заданиями планировщика из PowerShell

date07.04.2021
useritpro
directoryPowerShell, Windows 10, Windows Server 2016
commentsкомментариев 9

Большинство пользователей и администраторов привыкли использовать графический интерфейс консоли Taskschd.msc для создания заданий планировщика Windows (Task Scheduler), запускаемых по расписанию. Однако в различных скриптах и автоматизируемых задачах для создания заданий планировщика гораздо удобнее использовать возможности PowerShell. В этой статье мы покажем, как создавать и управлять заданиями планировщика Windows из PowerShell.

Управление заданиями Task Scheduler с помощью PowerShell

В Windows 10/Windows Server 2016 для управления задачами в планировщике используется PowerShell модуль ScheduledTasks. Список командлетов в модуле можно вывести так:

Get-Command -Module ScheduledTasks

  • Disable-ScheduledTask
  • Enable-ScheduledTask
  • Export-ScheduledTask
  • Get-ClusteredScheduledTask
  • Get-ScheduledTask
  • Get-ScheduledTaskInfo
  • New-ScheduledTask
  • New-ScheduledTaskAction
  • New-ScheduledTaskPrincipal
  • New-ScheduledTaskSettingsSet
  • New-ScheduledTaskTrigger
  • Register-ClusteredScheduledTask
  • Register-ScheduledTask
  • Set-ClusteredScheduledTask
  • Set-ScheduledTask
  • Start-ScheduledTask
  • Stop-ScheduledTask
  • Unregister-ClusteredScheduledTask
  • Unregister-ScheduledTask

powershell командлеты из модуля ScheduledTasks

Как создать задание планировщика с помощью PowerShell?

В современных версиях PowerShell (начиная с PowerShell 3.0 в Windows Server 2012/Windows 8) для создания заданию планировщика нужно использовать командлеты New-ScheduledTaskTrigger и Register-ScheduledTask.

Предположим, наша задача создать задание планировщика, которое должно запускаться при загрузке компьютера (или в определенное время) и выполнять какой-то PowerShell скрипт. Создадим задание планировщика с именем StartupScript_PS. Данное задание должно каждый день в 10:00 запускать PowerShell скрипт, хранящийся в файле C:\PS\StartupScript.ps1 из-под учетной записи системы (SYSTEM). Задание будет выполняться с повышенными привилегиями (галка “Run with highest privileges”).

$Trigger= New-ScheduledTaskTrigger -At 10:00am -Daily
$User= «NT AUTHORITY\SYSTEM»
$Action= New-ScheduledTaskAction -Execute «PowerShell.exe» -Argument «C:\PS\StartupScript.ps1»
Register-ScheduledTask -TaskName «StartupScript_PS» -Trigger $Trigger -User $User -Action $Action -RunLevel Highest –Force

Если задание успешно создано, появится надпись Ready.

создать задание планировщика с помощью Register-ScheduledTask

Теперь ваш PowerShell скрипт будет запускаться по указанному расписанию. Если на вашем компьютере настроена PowerShell Execution Policy, блокирующая запуск скриптов PS1, вы можете запустить скрипт их планировщика с параметром –Bypass.

Используйте такую строку при создании нового задания:

$Action= New-ScheduledTaskAction -Execute «PowerShell.exe» -Argument “-NoProfile -NoLogo -NonInteractive -ExecutionPolicy Bypass -File C:\PS\StartupScript.ps1″

Откройте консоль Taskschd.msc и проверьте, что проверьте, что в Task Scheduler Library появилось новое задание планировщика.

консоль Task Scheduler с новым заданием планировщика

$TaskName = «NewPsTask»
$TaskDescription = «Запуск скрипта PowerShell из планировщика»
$TaskCommand = «c:\windows\system32\WindowsPowerShell\v1.0\powershell.exe»
$TaskScript = «C:\PS\StartupScript.ps1»
$TaskArg = «-WindowStyle Hidden -NonInteractive -Executionpolicy unrestricted -file $TaskScript»
$TaskStartTime = [datetime]::Now.AddMinutes(1)
$service = new-object -ComObject(«Schedule.Service»)
$service.Connect()

Получение информации и запуск заданий планировщика из PowerShell

Вы можете вывести список всех активных заданий планировщика в Windows с помощью команды:

Get-ScheduledTask -TaskPath | ? state -ne Disabled

Чтобы получить информацию о конкретном задании:

Get-ScheduledTask CheckServiceState_PS| Get-ScheduledTaskInfo

информация о запуске задания Get-ScheduledTaskInfo

Вы можете отключить это задание:

Get-ScheduledTask CheckServiceState_PS | Disable-ScheduledTask

Чтобы включить задание:

Get-ScheduledTask CheckServiceState_PS | Enable-ScheduledTask

Чтобы запустить задание немедленно (не дожидаясь расписания), выполните:

отключить/включить/запустить задание планировщика с помощью PowerShell

Чтобы полностью удалить задание из Task Scheduler:

Unregister-ScheduledTask -TaskName CheckServiceState_PS

Если нужно изменить имя пользователя, из-под которого запускается задание и, например, режим совместимости, используйте командлет Set-ScheduledTask:

$task_user = New-ScheduledTaskPrincipal -UserId ‘winitpro\kbuldogov’ -RunLevel Highest
$task_settings = New-ScheduledTaskSettingsSet -Compatibility ‘Win7’
Set-ScheduledTask -TaskName CheckServiceState_PS -Principal $task_user -Settings $task_settings

Set-ScheduledTask : No mapping between account names and security IDs was done

Экспорт и импорт заданий планировщика в XML файл

С помощью PowerShell можно экспортировать любое задания планировщика в текстовый XML файл для распространения на другие компьютеры. Вы можете экспортировать задание из графического интерфейса Task Scheduler или из консоли PowerShell.

Следующая команда экспортирует задание StartupScript_PS в файл StartupScript_PS.xml:

Export-ScheduledTask «StartupScript_PS» | out-file c:\temp\StartupScript_PS.xml

Export-ScheduledTask - импорт задания планировщика в xml файла

schtasks /query /tn «NewPsTask» /xml >> «c:\ps\NewPsTask.xml»

После того, как настройки задания планировщика экспортированы в XML файл, его можно импортировать на любой другой компьютер с помощи графической консоли, SchTasks.exe или PowerShell.

Воспользуйте командлетом PowerShell Register-ScheduledTask чтобы параметры задания из файла и зарегистрировать его:

Register-ScheduledTask -Xml (Get-Content “\\Server1\public\NewPsTask.xml” | out-string) -TaskName «NewPsTask»

schtasks /create /tn «NewPsTask» /xml «\\Server1\public\NewPsTask.xml » /ru corp\aaivanov /rp Pa$$w0rd
schtasks /Run /TN «NewPsTask»

Обратите внимание, что в этом примере указаны данные учетной записи, из-под которой будет запускаться задание. Если имя и пароль учетной записи не указаны, то т.к. они не хранятся в задании, они будут запрошены при импорте.

Предыдущая статьяПредыдущая статья Следующая статья Следующая статья

How do I execute a PowerShell script automatically using Windows task scheduler?

I have one PowerShell script which sends emails. I want to execute that script automatically, every 1 minute. How can I do it, using task scheduler?

Currently I have created a task and provided the path of my script. But that scheduler opens my script, instead of executing.

I am using Windows 7 Professional and PowerShell version 2.0.5.

TylerH's user avatar

AK47's user avatar

 

7 Answers 7

Create the scheduled task and set the action to:

Arguments: -File «C:\Users\MyUser\Documents\ThisisMyFile.ps1»

Kevin_'s user avatar

Here is an example using PowerShell 3.0 or 4.0 for -RepeatIndefinitely and up:

Peter Mortensen's user avatar

Instead of only using the path to your script in the task scheduler, you should start PowerShell with your script in the task scheduler, e.g.

See powershell /? for an explanation of those switches.

If you still get problems you should read this question.

Peter Mortensen's user avatar

In my case, my script has parameters, so I set:

Arguments: -Command «& C:\scripts\myscript.ps1 myParam1 myParam2»

Peter Mortensen's user avatar

Carlos Coelho's user avatar

After several hours of test and research over the Internet, I’ve finally found how to start my PowerShell script with task scheduler, thanks to the video Scheduling a PowerShell Script using Windows Task Scheduler by Jack Fruh @sharepointjack.

Program/script -> put full path through powershell.exe

Add arguments -> Full path to the script, and the script, without any » «.

Start in (optional) -> The directory where your script resides, without any » «.

Weekend Scripter: Use the Windows Task Scheduler to Run a Windows PowerShell Script

Microsoft Scripting Guy, Ed Wilson, is here. The amount of emails that are generated when attempting to organize and to arrange an event such as PowerShell Saturday is amazing. Every day, it seems, there are nearly a dozen email messages about one detail or another. Windows PowerShell Microsoft MVP, Jim Christopher, is doing an excellent job of keeping things on track, and the Scripting Wife and Brian Wilhite have been hanging right in there with the work. The event truly will be a major big deal, and it will be fun as well as educational. It will be worth the time to register and to attend this event if you are in the Charlotte, North Carolina area on September 15, 2012.

Creating a Scheduled task to run a PowerShell script

The first thing I need to create a scheduled task to run a Windows PowerShell script is the command line that I will execute. The easy way to find this is to use the Run command. At times, I need to know what the command-line switches are for PowerShell.exe. To see these, I open Windows PowerShell and type powershell /? and then I examine the output that displays. The command and the output from the command are shown here.

Image of command output

When I know which switches to use, I practice my command via Run. The following image illustrates using Run to launch Windows PowerShell and to run a Windows PowerShell script. Keep in mind that this will open, and close Windows PowerShell, which is fine for a script producing a report. In testing, I often use the –noexit switch to see any errors arising from the operation.

Image of message

When I know the command line, I use the Task Scheduler tool, and create a new basic task. First, I need to assign a name and a description. I find it useful to provide a good description as well as a decent name because it facilitates performing maintenance on the task.

Image of menu

The next pane is the Task Trigger pane. It is pretty basic, and self-explanatory. Because I want to create a daily task, I leave that selected. After it is created, it is easy to edit the scheduled task to make it run the task more often, such as every hour if that is the need. One reason I use the Basic Task Wizard is that it is easy to get through the steps needed to create the basic task. I always edit stuff later. The Task Trigger pane is shown here.

Image of menu

Now it is time to set the schedule for the task. In this example, the task runs every morning at 7:00 AM beginning on August 11, 2012.

Image of menu

In the Action pane that follows, I select that we want the scheduled task to Start a program, and then click Next.

Image of menu

In the Start a Program pane, I cheat by placing the command I tested previously from the Run box into the Program/script box. I then click Next. The Start a Program pane is shown here.

Image of menu

Here is where the cheating part comes in to play. I used, directly, the command I tested in the Run box for my program. Rather than attempting to break things up, I simply copied the entire line. The Scheduled Task Wizard is smart enough to know what I wanted to do. It prompts, but it knows. The prompt appears here.

Image of message

When I have completed the Create Basic Task Wizard, I want to open the task and make a couple of additional changes. The easy way to do this is to select the Open the Properties dialog for this task when I click Finish, as shown here.

Image of menu

Because the task runs on a server, and because one might not be logged on to the server at the time the task is to run, it makes sense to tell the task to run whether or not the user is logged on. This opens a credential dialog, and allows me to set the password for the task. This option appears on the General tab of the scheduled job as shown in the image here.

Image of menu

When I have completed configuring the scheduled task, I always right-click the job and select Run. Then I examine the job history to ensure that the task completed properly. The History tab of the scheduled job is shown here.

Image of menu

Well, that is about all there is to creating a scheduled job to run a Windows PowerShell script. In Windows 8 and Windows Server 2012, there are Windows PowerShell cmdlets to create the scheduled job and to create the job triggers and actions—but that will be the subject of a later Hey, Scripting Guy! Blog post.

Запуск PowerShell скриптов по расписанию

Одним из несомненных достоинств PowerShell является то, что сценарии этого языка программирования очень удобно использовать для автоматизации периодически возникающих задач, добавив их в Планировщик задач.

Однако настроить запуск скриптов PowerShell по расписанию не так-то легко: простое указание в задаче ссылки на .ps1-файл ни к чему не приведет. Существует несколько хитростей, позволяющих использовать Планировщик задач для работы с PowerShell.

Запуск из vbs-скрипта

Проще всего настроить запуск Powershell-сценария по расписанию, добавив в Планировщик задач vbs-скрипт, который, в свою очередь, и будет запускать сценарий PowerShell.

Чтобы открыть Диспетчер задач, нажмите Пуск –> Выполнить –> введите в появившемся окне taskschd.msc и нажмите OK. Появится окно Диспетчера задач.

Планировщик заданий

Затем щелкнете по строке меню «Действие» и выбираем пункт «Создать задачу». Более подробную инструкцию можно прочесть в статьей Планировщик заданий.

Указывать путь к vbs-файлу необходимо в окне «Создание действия». Кликните по кнопке «Обзор» и укажите путь к vbs-скрипту.

 

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *