10.09.2024
Для запуска определенных действий по расписанию или при наступлении определенного события в Windows используется встроенный планировщик заданий (
Task Scheduler
). В этой статье мы рассмотри, как настроить автоматический запуск PowerShell скрипта с помощью планировщика задач Windows. Скрипт должен запускаться в фоновом режиме, не выдавать всплывающих окон и запускаться независимо от текущих настроек политики выполнения скриптов PowerShell.
В этом примере я хочу каждые 10 минут запускать PowerShell скрипт, который проверяет письма в почтовом ящике и, если есть новые письма с определенным отправителем и темой, отправляет содержимое в виде уведомления в Телеграм. Путь к файлу скрипта:
"C:\PS\OutlookEmailtoTG.ps1"
- Откройте консоль планировщика Task Scheduler, выполнив команду
taskschd.msc
. - Разверните дерево библиотеки Task Scheduler. Для удобства для хранения ваших кастомных заданий можно создать отдельную папку. Щелкните по ней и выберите Create Task
- На первой вкладке General нужно указать имя задания и пользователя, под которым оно будет запускаться. Задание может запускаться автоматически:
— когда пользователь вошел в систему пользователя (Run only the task is logged in)
— или независимо от того, выполнил ли пользователь вход или нет (Run whether user is logged on or not).
Второй режим используется чаще всего. Во втором случае можно указать, что задание будет запускаться от имени определенного пользователя (придется сохранить его пароль в диспетчер учетных данных Credentials Manager). Если для выполнения задания требуется повышение привилегий, нужно включить Run with highest privileges.Чтобы не использовать сохраненный пароль можно настроить запуск задания с максимальными привилегиями от имени NT AUTHORITY\SYSTEM. Для этого в поле User укажите
SYSTEM
.В среде AD можно настроить запуск заданий от имени сервисной учетной записи gMSA (пароль учетной записи gMSA не хранятся на компьютере в явном виде, вам не нужно их шифровать или защищать).
- На вкладке Триггеры (Triggers) нужно задать условие или время запуска задания планировщика. Например, чтобы запустить задание при входе пользователя, выберите тип триггера At log on и в поле Repeat task every выберите частоту повторного запуска каждые 10 минут.
- Если задание запускается от имени SYSTEM или пользователя с сохраненным паролем, нужно выбрать что задание должно быть запущено при загрузке Windows (At startup) и периодически перезапускаться.
- Либо с помощью триггера On a schedule можно настроить точное время запуска задания. У одного задания можно настроить несколько триггеров запуска.
- Затем перейдите на вкладку Actions. Здесь указывается, что нужно сделать при срабатывании любого из триггеров. В нашем случае мы хотим запустить PowerShell скрипт. Выберите New -> Start a program. Укажите следующе настройки задания:
Program/script:
powershell.exe
Add arguments (optional):
-ExecutionPolicy Bypass -NonInteractive -WindowStyle Hidden -File "C:\PS\OutlookEmailtoTG.ps1"
Рекомендуем предварительно проверить, что ваш PowerShell скрипт работает корректно. Воспользуйтесь, такой командой:
powershell.exe -file C:\PS\OutlookEmailtoTG.ps1 -NoExit
- При запуске скрипта используются следующие опции:
-File
– полный путь к файлу скрипта (PS1)
-ExecutionPolicy
— позволяет задать настройки выполнения PowerShell скриптов для текущего сеанса. Когда указано Bypass, текущие настройки политики игнорируются и скрипт будет выполнен в любом случае;
-NonInteractive
– не выводить интерактивные запросы к пользователю
-WindowStyle Hidden
– не показывать окно консоли PowerShell пользователю (скрипт запускается скрыто). Если задание планировщика настроено на запуск при входе пользователя в систему, при запуске скрипт может появляться и пропадать окно PowerShell. Морганий не будет только со скриптами, которые запускаются в сеансе 0 (вне зависимости от входа пользователя).-NoProfile
— если скрипт может работать без использования профиля пользователя, добавьте эту опцию. Она предотвращает загрузку профиля пользователя, что ускоряет выполнение скрипта; - На вкладке Settings можете включить следующие полезные опции:
Allow task to be run on demand — разрешить ручной запуск задания по запросу.
If the running task does not end when requested, force it to stop — завершить предыдущую задачу, если он не завершилась к моменту повторного запуска.
Do not start a new instance — не запускать новые экземпляры задания, если оно выполняется. - Сохраните настройки задания. Проверьте что задание появилось в консоли Task Scheduler. Чтобы протестировать работу задания, щелкните по нему и выберите Run.
Если PowerShell скрипт был успешно запущен, в поле Last Run Result появится сообщение The operation completed sucessfully (0x0).
- На вкладке History можно отслеживать историю и результаты предыдущих запусков задания. По умолчанию Task Scheduler не ведет историю запусков заданий. Включается с помощью кнопки Enable All Tasks History в правой панели Actions консоли.
Можно создать задание планировщика для запуска скрипта PowerShell из командной строки:
$TaskName="CheckMailbox"
$Trigger = New-ScheduledTaskTrigger -AtStartup
$Trigger.Repetition = (New-ScheduledTaskTrigger -once -at "12am" -RepetitionInterval (New-TimeSpan -Minutes 10) -RepetitionDuration (New-TimeSpan -Minutes 10)).repetition
$User= "NT AUTHORITY\SYSTEM"
$Action= New-ScheduledTaskAction -Execute "PowerShell.exe" -Argument "-ExecutionPolicy Bypass -NonInteractive -WindowStyle Hidden -File C:\PS\OutlookEmailtoTG.ps1"
Register-ScheduledTask -TaskName $TaskName -Trigger $Trigger -User $User -Action $Action -RunLevel Highest -Force
Некоторые дополнительные моменты, которые нужно учитывать при запуске скриптов PowerShell через планировщик заданий Windows:
- Если вы планируете выполнять скрипт в среде PowerShell Core 7.x, вместо powershell.exe нужно запускать pwsh.exe.
- Если к компьютеру, на котором запускается PowerShell скрипт с привилегированными правами имеют доступ другие пользователи, нужно изменить NTFS права доступа к файлу PS1 так, чтобы они не смогли его отредактировать.
- Если задание запускается от имени непривилегированного пользователя, его учетную запись нужно добавить в локальную политику безопасности Log on as a batch job (gpedit.msc -> Computer Configuration -> Windows Settings -> Security Settings -> Local Policies -> User Rights Assignment). При создании такого задания появится предупреждение: This task requires that the user account specified has Log on as batch job rights
- В домене AD PowerShell скрипты с помощью GPO можно запускать при загрузке/входе пользователя или выключении компьютера. Такие скрипт нызываются логон-скриптами.
Introduction
Windows Task Scheduler enables users to schedule tasks to run at a specific date and time, on a defined schedule, or when triggered by certain events. This built-in tool of Windows operating systems helps improve efficiency and ensure reliable execution of repetitive tasks. In this blog, we will show you how to run a PowerShell script from Task Scheduler and how to create scheduled tasks using PowerShell.
Setting Up PowerShell Scripts for Automation
Understanding Task Scheduler
The Task Scheduler library is a collection of all defined tasks, organized into folders. For each task, the GUI provides the following tabs:
- General — The tasks’ name and description, the account it should run under, and other security options.
- Triggers — The conditions that start a task, which can be time-based (e.g., daily, weekly), event-based (e.g., at system startup or user login), or custom
- Actions — The operations executed when a task is triggered, such as starting a program.
- Conditions — Criteria that control the execution of a task based on the state of the computer, such as only running when the computer is idle for a specific period
- Settings — Additional configurations that determine how and when a task is run, such as restarting a task if it fails or stopping it if it runs longer than expected
- History — A history of task executions, including start times, end times, and any errors or warnings encountered
Benefits of using Task Scheduler for Automating PowerShell Scripts
Automating PowerShell scripts through the PowerShell Task Scheduler offers many benefits, including the following:
- Time savings — When you run PowerShell scripts from Task Scheduler, you can save a considerable amount of time that would otherwise be spent on manual execution. This is particularly beneficial for scripts that need to run during off-hours.
- Consistency — Automation reduces the risk of human errors. A scheduled PowerShell script will execute exactly the same operations in the same order every time.
- Reliability — With Task Scheduler, you can ensure that critical maintenance tasks, such as backup and cleanup routines, are executed regularly. This increases the system’s reliability and reduces the risk of data loss or system failures.
- Resource efficiency — By scheduling scripts to run during periods of low system utilization, you can ensure that intensive tasks do not degrade system performance during peak hours.
- Flexibility — Task Scheduler offers a variety of scheduling options, including the ability to run tasks at system startup, on logon, when idle or in response to specific events. This level of control enables you to tailor script execution to your specific requirements.
- Error handling — You can configure scheduled tasks to attempt a rerun if a script fails, send emails upon task completion or failure, and write event logs. This enables timely troubleshooting and keeps you informed about the health of automated processes.
- Security — With Task Scheduler, PowerShell scripts can run under specific user accounts, including those with elevated privileges, without requiring the user to be logged on. This helps ensures that sensitive tasks are executed securely and allows for the automation of scripts that require higher privileges. However, since adversaries can exploit scheduled and triggered tasks for malicious purposes, you should leverage an auditing or tracking system to monitor tasks for potential abuse. Netwrix Access Analyzer is a good example of a tool that can mitigate malicious activity.
- Integration and extensibility — Scheduling PowerShell scripts allows for sophisticated automation scenarios that can react to system events, orchestrate multiple tasks and more.
- Management of complex workflows — Task Scheduler can manage complex workflows, such as chaining tasks together or using conditional logic based on the success or failure of a prior task. This is invaluable for scenarios where multiple, interdependent tasks need to be carefully orchestrated.
- Ease of use — Despite its powerful features, Task Scheduler has an intuitive graphical interface that simplifies the process of setting up and managing automated tasks. For more advanced users, Task Scheduler can also be configured and managed using command-line tools or PowerShell cmdlets.
Steps to Create a Schedule for a PowerShell Script
Before scheduling a PowerShell script with Task Scheduler, make sure the script is saved with the extension .ps1 and that it has been tested to ensure it functions correctly.
Then take the following steps:
- Open Task Scheduler: Press Win + R, type taskschd.msc to the Run dialog and press Enter.
- In the Actions pane on the right, click Create Task.
- On the General tab, do the following:
- Enter a name and description for your task.
- Configure the appropriate security options. For example, selecting Run whether user is logged on or not will ensure the task runs even if you are not logged in. If the script requires administrative rights, check Run with highest privileges.
Click OK to save your changes.
- Go to the Triggers tab and click New. In the New Trigger pane, choose the following:
- When the task should begin
- The frequency at which it should run, such as once, daily or weekly
- Any additional options you need, such as stopping the task if it runs longer than the time you specify
Click OK to save your changes.
- Go to the Actions tab.Click New to set up a new action to run your PowerShell script:
- From the Action dropdown menu, select Start a program.
- In the Program/script field, enter powershell.exe.
- In the Add arguments field, enter the following, making sure to specify the full path to your script: -File C:\Scripts\scriptname.ps1
- In the Start in field, specify the directory where the script, if needed. This is typically not required unless your script relies on relative paths.
Click OK to save your changes
- Click OK and go to the Conditions tab. St any conditions under which the task should run. For example, you can specify that the task should run only if the computer is on AC power or only if it is connected to a specific network. Click OK to save your selections.
- Next, go to the Settings tab and configure the following:
- Allow task to be run on demand — Check this if you want to be able to manually run the task.
- If the task fails — Specify what should happen if the task fails, such as restarting the task.
- Stop the task if it runs longer than — Set a time limit if applicable.
- If the task is already running — Choose what should happen if the task is triggered but it is already running.
- Click OK to finalize your task. You will be prompted to enter credentials for the user account under which the task will run.
Advanced Configuration and Best Practices
Controlling Script Execution and Visibility
To control script execution and visibility when using Task Scheduler, you can use the following parameters in the Add arguments field of the Action tab:
- NoExit — Add this parameter to prevent the PowerShell or command prompt window from closing automatically after the script has run. This option is useful for debugging or when you want the console window to stay open to check the output directly.
- Command — Use this parameter to specify the full path of a script to execute and any necessary arguments.
For example, you might specify the following in the Add arguments field:
-NoExit -Command -File C:\Scripts\InstallOfSoftware.ps1
Redirecting Output to a Text File or Other Destinations to Log Script Activity
Troubleshooting Common Windows Task Scheduler Issues
Here are some common issues that can prevent your scheduled tasks from running as expected and how to resolve them.
Task will not start or run.
- Make sure the user account running the task has the necessary permissions to execute the task and access any files or directories referenced by the task.
- Double-check the task’s configuration settings, such as the trigger settings, action parameters and conditions.
- Ensure the task is enabled.
- If the task uses a specific user account to run, check whether the password has been changed and update it for the task if necessary.
Task runs manually but not automatically.
- Verify the trigger settings are correct; common issues include incorrect start times, misconfigured schedules.
- Check for conditions that might prevent the task from running, such as that it will run only if the computer is idle for a specific time. If the task is scheduled to run during idle times or when the computer is not in use, power settings like sleep or hibernation mode can prevent execution. Adjust power settings to ensure the system remains active for the task to run.
Task stops unexpectedly or behaves incorrectly.
- Check whether there is enough memory, CPU or disk space available for the task to run smoothly.
- If the task involves running a script, ensure the script runs correctly outside of Task Scheduler. Consider how environment variables, paths or permissions might differ in the two situations.
Task fails with specific error codes.
Look up the error code provided in the task’s history or event log to get current information on the issue and how to resolve it.
Task runs but does nothing.
- Verify that the action set for the task, e.g., starting a program, is configured correctly.
- If the script is not executing due to policy restrictions, consider adding the -ExecutionPolicy Bypass argument to override the system’s execution policy and allow the script to run.
- Make sure paths to executable files or scripts are correct, and any command-line arguments are properly specified.
- If the task should output to a file or other destination, ensure the paths are correct and the running account has the necessary write permissions.
Practical Examples for Common Use Cases
Example Scripts for Common Administrative Tasks
Below are some practical use cases for common administrative tasks that you might want to automate using Windows Task Scheduler, along with sample scripts.
Back up a Folder
The following script can be used to back up a folder in C drive to a folder in local D drive:
Copy-Item -Path "C:\Source\*" -Destination "D:\Backup" -Recurse -Force
Install Software Updates
To update software or system components automatically, use this script:
Install-WindowsUpdate -AcceptAll -AutoReboot
Send User Notifications
To send reminders about upcoming events to an email distribution list, use this script:
Send-MailMessage -To "AbbeyCrawford@milkyway.com" -From "AbbeyTucker@milkyway.com" -Subject "Daily Meeting Reminder" -Body "This is a reminder about the meeting scheduled for 10:00 AM." -SmtpServer "smtp.milkyway.com"
Perform Security Scans
To automatically run security scans to detect malware or vulnerabilities, use this script:
Start-MpScan -ScanType QuickScan
Clean Up Temporary Files
This script removes temporary files from the specified directories:
Get-ChildItem -Path C:\Windows\Temp\*, $env:TEMP\* -Recurse | Remove-Item -Force -Recurse -ErrorAction SilentlyContinue
Restart a Service
To restart a service, such as a web server or Microsoft SQL server service, you can use commands like the following:
Restart-Service -Name W3SVC
Restart-Service -Name MSSQLSERVER
Scheduling Complex PowerShell Scripts
You can schedule more complex PowerShell scripts as well. As illustrated in the examples below, it’s a best practice to include comments that describe the purpose of the various sections of a script.
Report on Disk Space Usage
This script provides a quick overview of disk space usage:
# Script to report disk space usageGet-PSDrive -PSProvider FileSystem |
Select-Object Name, @{Name="UsedGB";Expression={"{0:N2}" -f (($_.Used - $_.Free)/1GB)}}, @{Name="FreeGB";Expression={"{0:N2}" -f ($_.Free/1GB)}}, @{Name="TotalGB";Expression={"{0:N2}" -f ($_.Used/1GB)}} |
Format-Table -AutoSize
Monitor System Health
To track system performance over time, you can use this PowerShell script to log CPU usage, memory usage and disk space to a file:
# Define the log file path$logFile = "C:\SystemHealthLog.txt"
# Function to get system health metrics
function Get-SystemHealth {
# Get CPU usage
$cpuUsage = Get-Counter '\Processor(_Total)\% Processor Time'
# Get memory usage
$memoryUsage = Get-Counter '\Memory\Available MBytes'
# Get disk space usage for C: drive
$diskSpace = Get-PSDrive -Name C
$usedSpace = $diskSpace.Used / 1MB
$freeSpace = $diskSpace.Free / 1MB
$totalSpace = $diskSpace.Used + $diskSpace.Free / 1MB
# Format output
$cpuUsageFormatted = "{0:N2}%" -f $cpuUsage.CounterSamples[0].CookedValue
$memoryUsageFormatted = "{0:N2} MB" -f $memoryUsage.CounterSamples[0].CookedValue
$diskSpaceFormatted = "Used: {0:N2} MB, Free: {1:N2} MB, Total: {2:N2} MB" -f $usedSpace, $freeSpace, $totalSpace
# Write to log file
$logEntry = "Date and Time: $(Get-Date) - CPU Usage: $cpuUsageFormatted, Memory Available: $memoryUsageFormatted, Disk Space: $diskSpaceFormatted"
Add-Content -Path $logFile -Value $logEntry
}
# Run the health check
Get-SystemHealth
Modifying or Deleting Scheduled Tasks
Before you modify or delete one or more scheduled tasks, you might want to review all existing tasks. To see the list of tasks, simply run the Get-ScheduledTask cmdlet.
Modifying a Scheduled Task
To modify a task, right-click on it and select Properties, as shown below. Then edit the required settings and click OK to save your changes.
Deleting a Scheduled Task
To delete a scheduled task, right-click on it, select Delete and confirm the action.
Creating Scheduled Tasks with PowerShell Scripts
Introduction to PowerShell Scheduling
To create scheduled tasks, you have another option in addition to Task Scheduler: PowerShell. Creating and managing scheduled tasks directly from the PowerShell interface scheduling can significantly enhance productivity, accuracy and session reliability, especially when managing remote systems through a CimSession.
Below are some of the main PowerShell commands used to create and manage scheduled tasks:
- New-ScheduledTask — Creates a new scheduled task object in PowerShell
- Register-ScheduledTask — Registers a new scheduled task
- New-ScheduledTaskAction — Defines scheduled task actions
- New-ScheduledTaskPrincipal — Stores the user account under which the task will run
- New-ScheduledTaskSettingsSet — Defines scheduled task settings
- New-ScheduledTaskTrigger — Defines scheduled task triggers
Advantages of Using PowerShell for Managing Scheduling Tasks
The benefits of using PowerShell to run scheduled tasks include the following:
- Ease of use — It’s easy to specify complex triggers, conditions and actions.
- Flexibility — You can write and execute sophisticated scripts that can perform a wide range of tasks, from simple file cleanups to intricate system diagnostics and repairs.
- Time savings — Using a PowerShell scheduled task to run a PowerShell script eliminates the need to manually perform repetitive or complex tasks.
- Easier troubleshooting — PowerShell scripts can log detailed information about errors or even attempt to rectify them automatically.
- Remote execution — Scheduled tasks can be executed and throttled across multiple machines. This is particularly beneficial in larger network environments.
- Security — PowerShell includes many security features, such as execution policy and signed scripts, to help ensure that only authorized scripts run on your system.
- Efficiency — Using PowerShell for scheduling tasks usually consumes less system resources than third-party automation tools.
- Adaptability — Scheduled tasks in PowerShell can be easily modified, replicated or extended to meet evolving needs.
Creating a Scheduled Task with PowerShell
A PowerShell script for creating a scheduled task includes the following elements:
- $action — This specifies what the task will do, such as running a PowerShell script, launching an application or executing a command:
$action = New-ScheduledTaskAction -Execute "PowerShell.exe" -Argument "-File C:\Scripts\InstallOfSoftware.ps1"
- $trigger — This specifies when the task will run, such as at a specific time, daily or weekly, or based on system events:
$trigger = New-ScheduledTaskTrigger -Daily -At "10:00AM"
- $principal — This specifies the user account under which the task will run:
$principal = New-ScheduledTaskPrincipal -UserId “NT AUTHORITY\SYSTEM” -LogonType Password
- $settings — This includes options like how to handle task failures, conditions for running and behavior on battery power:
$settings = New-ScheduledTaskSettingsSet -AllowStartIfOnBatteries -DontStopIfGoingOnBatteries -StartWhenAvailable
- Register-ScheduledTask — This registers the task with the Task Scheduler:
Register-ScheduledTask -TaskName “Installation of Software" -Action $action -Trigger $trigger -Principal $principal -Settings $settings
Below you can see execution of the complete script:
Security Considerations and Best Practices
Security Implications of Scheduled Tasks
When you schedule tasks, whether it’s using Task Scheduler or PowerShell, be sure to pay attention to the following security concerns:
- Permission management — Scheduled tasks run with the permissions of the account under which they are scheduled, so they can be abused. This risk is higher if the account has elevated access. Be sure to run scheduled tasks using accounts that have the minimum necessary permissions.
- Script security — The scripts or executables called by scheduled tasks can themselves be vectors for security vulnerabilities. For example, malicious actors can replace or modify scripts stored in unprotected directories to execute harmful commands.
- Process hijacking — If a scheduled task is predictable and runs with high privileges, an attacker might replace the script that the task is supposed to execute with malicious code.
- Auditing and accountability — It’s essential to keep detailed logs of scheduled task creation, modification and execution in order to detect and respond to malicious activity.
- Denial of service — By scheduling tasks that consume excessive system resources to run at critical times, an attacker could disrupt the host system’s ability to perform its intended functions.
Running Scripts with the Appropriate Security Context and the Implications of Using Highly Privileged Accounts
To minimize your attack surface, always run scripts under an account that has the least privilege necessary for the task, and avoid running scripts with administrative rights. To accomplish this, understand what resources, permissions and throttle limits a script requires. For example, does the script need to modify system files, access specific data or communicate over the network?
In addition, use execution policies to control the conditions under which scripts can run. For example, you can restrict the system to run scripts only if they are signed by a trusted publisher.
For scripts that need to run as a service, consider using a Windows managed service account (MSA) or group managed service account (gMSA), which are more secure because their passwords are automatically managed.
Best Practices for Creating Scheduled Tasks
To maximize the benefits of using scheduled tasks, follow these best practices:
- Make sure each task has a clear purpose. Document both what the task does and why it’s needed to help others who might work with the task in the future.
- Establish clear naming conventions. To prevent confusion and improper task execution, ensure that each scheduled task has a unique taskpath.
- Review and test. Carefully review scripts before running them, especially if they are obtained from external sources, with an eye for any suspicious code. Before deploying a scheduled task in a production environment, thoroughly test it in a staged or development environment. It is also a good practice to maintain a repository of approved scripts.
- Implement error handling. Make sure every script can manage common errors gracefully and alert relevant team members when there’s an issue that needs attention.
- Understand dependencies. If a task depends on external services or data, ensure there are checks for availability and graceful handling of outages or delays.
- Consider resource usage. Look for ways to make tasks less resource-intensive, such as by modifying its logic or running frequency. Tasks should be run as frequently as necessary but not so often that they create performance issues. When choosing when tasks run, consider factors like other system activity and potential conflicts.
- Pay attention to security. In addition to the security guidelines provided above, be sure to use appropriate authentication and authorization measures for tasks that require access to secure resources, and make sure that tasks do not inadvertently expose sensitive data.
- Avoid relying on default settings for critical tasks. Customize task configurations to suit your specific needs.
- Store scripts in a secure location. Make sure only users who need to run or modify the scripts have access.
- Sign your scripts. Whenever possible, sign your scripts with a digital certificate issued by a trusted Certificate Authority (CA). This not only verifies the authorship of the script but also ensures that the script has not been tampered with since it was signed.
- Implement monitoring and alerting. Logs are invaluable for diagnosing issues and understanding a task’s actions. Tools that notify administrators of unusual script activity or performance degradation enable quicker response.
- Regularly review and update scheduled tasks. This includes updating any dependencies, adjusting schedules based on new business needs, and retiring tasks that are no longer necessary.
Conclusion
Windows Task Scheduler enables business users and administrators to run PowerShell scripts at specific dates and times on a regular basis, such as daily or weekly, or when specific conditions are met. Automating tasks using Task Scheduler saves time while ensuring that tasks are performed accurately and reliably. More advanced users can use PowerShell to create and manage scheduled tasks.
When scheduling scripts, make sure to follow best practices such as documenting the purpose of the task, using error handling and logging within the scripts, and using the least privilege principle to avoid excessive permissions, which can be a security threat if compromised and used by adversaries.
FAQ
What is Windows Task Scheduler?
Windows Task Scheduler is a built-in tool in the Windows operating system that enables users to schedule tasks and processes to run automatically. With Task Scheduler, you can set up tasks to run at a specified day and time or at a certain interval like daily or weekly.
Why should I use Task Scheduler to automate PowerShell scripts?
By choosing to run PowerShell scripts from Task Scheduler, you can automate repetitive tasks, which ensures that they are performed reliably and accurately without further effort on your part.
How do I open Task Scheduler?
Press Win + R to open the Run dialog. Type taskschd.msc and press Enter.
How do I create a new task in Task Scheduler?
Click on Create Task in the Actions pane on the right side of the Task Scheduler window. Provide a name and description for the task; choose appropriate settings for the Action, Triggers, Conditions and Settings tabs; and click Save.
What are the benefits of naming and describing a task?
Providing a useful name and clear description that explains what the task does and why it is needed helps ensure that each task has a clear purpose and facilitates future maintenance by others who work with the task.
How do I determine the trigger for a scheduled task?
On the Trigger tab for a task, you can specify when the task should run, such as on schedule, at system startup or upon user logon, as well the repetition interval and other criteria.
How do I configure Task Scheduler to run a PowerShell script?
- Go to the Actions tab, click New andselect Start a program from the dropdown menu.
- In the Program/script field, input powershell.exe.
- In the Add arguments field, enter the following, replacing the argument InstallofSoftware.ps1 with the name of your script:
-File C:\Scripts\InstallofSoftware.ps1
How can I set up tasks to run even when the user is not logged on?
On the General tab of the task, select the option Run whether a user is logged on or not.
How do I manage task privileges and ensure scripts stop after a specified duration?
Tasks have the privileges of the account they are run under. You can specify the account to run the task on the General tab.
To ensure a script stops after a given duration, on the Settings tab, select Stop the task if it runs longer than and choose the desired number of hours or days.
How do I control script execution visibility?
You can control script execution and visibility by adding the -NoExit or -Command parameter in the Add Argument field on the Action tab.
What tips can help troubleshoot tasks that do not run as expected?
Password expiration or changes can cause a task to fail. Improperly configured or maliciously designed scheduled tasks (for example, tasks that consume excessive system resources) can lead to a denial of service on the host machine, hurting its availability and performance.
How do I modify an existing scheduled task?
Right-click on the task in the Windows Task Scheduler library, select Properties and make the desired changes to the task’s settings.
How do I delete a scheduled task?
Right-click on the task in the Task Scheduler library and choose Delete.
What are the advantages of using PowerShell for scheduling tasks?
Compared to the Task Scheduler GUI, PowerShell provides more granular control over task configuration, error handling and logging, and makes it easier to define custom scheduling logic. PowerShell also enables you to schedule and run tasks on multiple remote systems from a central location.
What are the New-ScheduledTaskTrigger and Register-ScheduledTask cmdlets used for?
The New-ScheduledTaskTrigger cmdlet is used to define triggers for the task, and the Register-ScheduledTask cmdlet is used to register the task with Windows Task Scheduler.
What are the security implications of scheduled tasks?
Running a scheduled task with a highly privileged accounts increases security risks if the account is compromised, so always choose the account with the least privilege principle in mind.
How should I run scripts with the appropriate security context?
Most important, run scripts under an account with the least privileges necessary to complete the task, and use managed service accounts (MSAs) or group managed service accounts (gMSAs) when appropriate. Consider using execution policies to allow restrict only scripts that are signed by a trusted publisher, and whenever possible, sign your scripts with a digital certificate issued by a trusted Certificate Authority.
What are the best practices for organizing and managing scheduled tasks?
Key best practices include storing scripts in a secure location with access permissions controlled and evaluating scripts in a test environment before implementing them in production.
Since 2012, Jonathan Blackwell, an engineer and innovator, has provided engineering leadership that has put Netwrix GroupID at the forefront of group and user management for Active Directory and Azure AD environments. His experience in development, marketing, and sales allows Jonathan to fully understand the Identity market and how buyers think.
You can use Task Scheduler in Windows to automate the execution of a PowerShell script by creating a new task and configuring it to run the script at specified times or events.
Here’s a basic code snippet to run a PowerShell script:
Start-Process powershell -ArgumentList '-NoProfile -ExecutionPolicy Bypass -File "C:\Path\To\YourScript.ps1"'
Understanding Task Scheduler
What is Task Scheduler?
Windows Task Scheduler is a built-in tool that allows users to automate tasks based on specific triggers and conditions. This can range from simple actions like playing a sound to complex sequences involving running scripts or programs. By automating routine tasks, it offers significant time savings and increased efficiency.
Why Use PowerShell Scripts with Task Scheduler?
PowerShell is a powerful command-line shell and scripting language designed for task automation and configuration management. By integrating PowerShell scripts with Task Scheduler, you can perform complex administrative tasks without manual intervention. This combination is particularly useful for automating repetitive systems management tasks, backing up files, or generating reports.
Task Scheduler Not Running PowerShell Script: A Quick Fix Guide
Preparing Your PowerShell Script
Creating a PowerShell Script
Creating a PowerShell script begins with writing the commands you want to execute. Here’s a simple example:
# Simple PowerShell Script Example
Get-Process | Where-Object {$_.CPU -gt 100} | Select-Object Name, CPU
This script retrieves all processes that consume more than 100 CPU cycles, allowing you to monitor and manage resource usage effectively.
Saving Your PowerShell Script
Scripts should be saved with a `.ps1` file extension. Choose descriptive names that outline the script’s purpose, such as `HighCPUProcesses.ps1`. Additionally, organize your scripts in dedicated directories to maintain a clean working environment.
Run Task Scheduler From PowerShell: A Quick Guide
Scheduling a PowerShell Script to Run in Task Scheduler
Accessing Task Scheduler
To access Task Scheduler, search for it in the Start menu or explore it through the Control Panel under Administrative Tools. Familiarize yourself with the interface, noting key areas like the Task Scheduler Library, where all scheduled tasks are listed.
Creating a New Basic Task
Starting the New Task Wizard is straightforward:
- Select Create Basic Task from the right panel.
- Fill in essential details, such as the `Task name` and `Description`.
- Choose one of the triggers (e.g., daily, weekly) that describes when you want your script to run.
Launching PowerShell via Task Scheduler
In the Action section of the wizard, choose “Start a Program.” You’ll be prompted to enter the following:
- Program/script: Here, enter `powershell.exe`.
- Add arguments (optional): This is where you specify how PowerShell should execute your script. Use the following format:
-ExecutionPolicy Bypass -File "C:\Path\To\YourScript.ps1"
This command ensures that the script runs without being halted by execution policy restrictions.
Execute PowerShell Script: A Step-by-Step Guide
Advanced Scheduling Options
Setting Triggers for Your Task
When configuring your task, specify when it should trigger. This can be done through various options:
- Daily: Choose a specific time each day.
- Weekly: Select specific days of the week for execution.
- On startup: Automatically execute your script whenever the computer starts.
Tailoring the triggers to your specific needs maximizes the utility of your scheduled task.
Configuring Conditions and Settings
Exploring conditions can optimize how the task runs. For instance:
- Start the task only if the computer is on AC power: Useful for laptops to conserve battery life.
- Stop the task if it runs longer than: Helps to prevent infinite loops or excessively long-running tasks.
Other settings allow you to refine how the task behaves, such as restarting if it fails.
Power Automate Run PowerShell Script: A Quick Guide
Testing and Troubleshooting
Running Your Scheduled Task
After completing your setup, it’s vital to test your scheduled task. This can be done by right-clicking on the task in Task Scheduler and selecting Run. Observe if the script executes as intended and check for any immediate output.
Troubleshooting Common Issues
If the task does not run as expected, consider common issues:
- Access Denied: Ensure that the user account under which the task runs has the necessary permissions.
- Script not executing: Check the file path and ensure there are no typos or incorrect paths. The Event Viewer can also provide insight into error messages.
Batch File to Run PowerShell Script: A Quick Guide
Best Practices for Running PowerShell Scripts via Task Scheduler
Managing Security and Permissions
It’s imperative to understand the security implications of running scripts via Task Scheduler. Ideally, use a service account specifically created for this purpose that has just enough permission to execute the tasks it needs without exposing unnecessary system areas to risk.
Logging and Monitoring Your Scripts
Implement logging within your PowerShell scripts to capture important runtime information and outcomes. You can do this using the following code snippet:
# Logging Example
$logFile = "C:\Path\To\LogFile.txt"
"Script started at $(Get-Date)" | Out-File -FilePath $logFile -Append
Additionally, regularly review the Task Scheduler logs to monitor task performances and outcomes.
Import Scheduled Task PowerShell: A Quick Guide
Conclusion
Automating tasks using Task Scheduler with PowerShell scripts profoundly enhances productivity and efficiency. By following the guidance laid out here, you can effortlessly schedule scripts to run at your desired times with minimal manual intervention.
Always feel free to explore more complex scripts and modify them to suit your tasks. Share your experiences and community insights as the PowerShell ecosystem grows and evolves!
Mastering Selenium PowerShell: Quick Guide and Tips
Additional Resources
Check official Microsoft documentation for deeper insights and advanced tips into using Task Scheduler and PowerShell effectively. Additionally, consider browsing popular PowerShell blogs and forums for further learning and community support.
Install-Module PnP.PowerShell: A Quick Start Guide
FAQs
What is the difference between running a script manually and via Task Scheduler?
Running a script manually requires user initiation, whereas scheduling through Task Scheduler allows the script to execute at designated times without intervention, ideal for routine tasks.
Can I run PowerShell scripts without administrative rights?
Yes, but administrative privileges may be necessary depending on what the script is trying to access or modify, especially if system-level changes are involved.
What should I do if my scheduled task fails?
Start troubleshooting by checking permissions, reviewing paths for correctness, and consulting the Event Viewer for specific error messages.
In Windows, the built-in Task Scheduler can be used to perform an action according to a schedule or when a certain event occurs. This guide explains how to configure a PowerShell script to run automatically by using the Windows Task Scheduler. The PS1 script should run in the background, display no pop-ups, and run regardless of the current PowerShell script execution policy settings.
In this example, I want to run the C:\PS\Outlook_Email_to.ps1
PowerShell script file every 10 minutes.
- Open the Task Scheduler console by running
taskschd.msc
command - Expand the Task Scheduler library tree. For convenience, create a separate folder for your custom scheduled tasks. Right-click and select Create Task.
- In the General tab, specify the task name and the user it will run under. The task can run automatically:
– when the specific user is logged in (
Run only the task is logged in
)– or whether the user is logged in or not (
Run whether user is logged on or not
).The second mode is used most often. In the second case, you can specify that the task should run on behalf of a specific user (the Credentials Manager used to store the user’s password). If the task requires elevation, enable the ‘Run with highest privileges‘ option.
To avoid using a stored password, you can configure the Task to run as NT AUTHORITY\SYSTEM with the highest privileges. For that, enter
SYSTEM
in the User field.
In an AD environment, the scheduled tasks can run on behalf of the gMSA managed service accounts. - In the Triggers tab, specify the condition or time for the Scheduler task to start. For example, to run a task when a user logs in, select the ‘At log on‘ trigger and select a frequency of 10 minutes in the ‘Repeat task every‘ option.
- If the task runs on behalf of SYSTEM or a user with a stored password, select to run the task when Windows starts (At startup) and to restart it periodically.
- Or use the On a schedule trigger to set the exact time for the task to start. Multiple start triggers can be configured for a single task.
- Then go to the Actions tab. Specify the action to be taken when any of the triggered events occur. I want to run a PowerShell script in this case. Select New -> Start a program. Configure the following action settings:
Program/script:powershell.exe
Add arguments (optional):-ExecutionPolicy Bypass -NonInteractive -WindowStyle Hidden -File "C:\PS\Outlook_Email_to.ps1"
Before running the script through the Task Scheduler, check that it returns no errors in unattended mode. Use the following command:
powershell.exe -file C:\PS\ Outlook_Email_to.ps1 -NoExit
- The following options are used to run a PowerShell script:
-File
– full path to the script file (PS1)
-ExecutionPolicy
— Set PowerShell script execution policy settings for the current session. Current policy settings are ignored and the script is executed anyway if Bypass is specified;
-NonInteractive
– Do not display interactive prompts to the user
-WindowStyle Hidden
– Hide the PowerShell console window from the user (the script runs hidden). The PowerShell prompt window may appear and disappear momentarily while the script is running if the scheduler task is set to run when the user logs on. There is no flashing prompt only for scripts started in console session 0 (regardless of user login).
-NoProfile
— add this option if the script can work without a user profile. It prevents the user profile from being loaded, which speeds up the execution of the script; - You can enable the following useful options in the Settings tab:
Allow task to be run on demand
If the running task does not end when requested, force it to stop
Do not start a new instance - Save the task settings. Check that the new task appears in the Task Scheduler snap-in. Click on a task and select Run to test it.
If the PowerShell script has been run successfully, a message will be displayed in the Last Run Result:
The operation completed sucessfully (0x0).
To log all actions to a text log file, we recommend that you add a simple logging function to the PowerShell script. This allows viewing detailed information on all actions performed at any time.
- Use the History tab to view the history and results of previous Task runs. Task History is not saved by default in Task Scheduler (click the Enable All Tasks History link in the Actions pane).
You can also create such a Scheduler task to run a PowerShell script from a command prompt:
$TaskName="CheckOutlookMailbox"
$Trigger = New-ScheduledTaskTrigger -AtStartup
$Trigger.Repetition = (New-ScheduledTaskTrigger -once -at "12am" -RepetitionInterval (New-TimeSpan -Minutes 10) -RepetitionDuration (New-TimeSpan -Minutes 10)).repetition
$User= "NT AUTHORITY\SYSTEM"
$Action= New-ScheduledTaskAction -Execute "PowerShell.exe" -Argument "-ExecutionPolicy Bypass -NonInteractive -WindowStyle Hidden -File C:\PS\Outlook_Email_to.ps1"
Register-ScheduledTask -TaskName $TaskName -Trigger $Trigger -User $User -Action $Action -RunLevel Highest -Force
There are some additional things to consider when running PowerShell scripts through the Windows Task Scheduler:
- To run the script in the PowerShell Core environment, run
pwsh.exe
instead ofpowershell.exe
. - If other users have access to the computer on which you are running the PowerShell script with privileged rights, make sure that you have changed the NTFS access permissions on the PS1 file so that they cannot modify it.
- If the task is run as an unprivileged user, their account must be added to the local security policy Log on as a batch job (gpedit.msc -> Computer Configuration -> Windows Settings -> Security Settings -> Local Policies -> User Rights Assignment). A warning will appear when creating such a task:
This task requires that the user account specified has Log on as batch job rights
- In an AD domain, you can use the GPO to run PowerShell scripts when a user logs on or off, or when a computer starts or shuts down. Such scripts are known as logon scripts.
Post Date:
– Last Modified:
Automating PowerShell scripts is a much needed task for Windows Administrators. The Task Scheduler provides a reliable way to execute scripts on a predefined schedule, eliminating the need for manual intervention. This guide covers both the command and GUI methods for how to run PowerShell scripts from Task Scheduler.
Whether you are automating system maintenance, log collection, or other administrative tasks, using Windows Task Scheduler will serve you well. As a SQL Server DBA, I would usually have my PowerShell & SQL scripts running on a schedule using the SQL Agent. However, as I’ve mentioned in my other post, we need to use other methods like the Task Scheduler for achieving automation when on the SQL Server Express Edition.
Topics Covered:
> Create a Scheduled Task using PowerShell
> Create a Scheduled Task for a PowerShell Script (GUI Option)
> More Tips for Automating PowerShell Scripts
Create Scheduled Task using PowerShell
1. Create Your PowerShell Script
Write the PowerShell script you want to schedule. For this example, the script logs the system’s average CPU usage with a timestamp into a text file. Save your script, e.g., avg_cpu_collector.ps1
, in C:\temp\PowerShell_Scripts
.
2. Create the Scheduled Task
Use the following PowerShell code to create a scheduled task that runs your script daily at 8:05 AM:
$actions = (New-ScheduledTaskAction -Execute 'C:\temp\PowerShell_Scripts\avg_cpu_collector.ps1') $principal = New-ScheduledTaskPrincipal -UserId 'Administrator' -RunLevel Highest $trigger = New-ScheduledTaskTrigger -Daily -At '8:05 AM' $settings = New-ScheduledTaskSettingsSet -WakeToRun $task = New-ScheduledTask -Action $actions -Principal $principal -Trigger $trigger -Settings $settings $taskPath = '\Admin\' # create new scheduled task as per parameters above Register-ScheduledTask 'DailyPSCollector' -InputObject $task -TaskPath $taskPath
3. Verify the Task
Open Task Scheduler to confirm the task was created under the specified path (\Admin\
).
Create a Scheduled Task for a PowerShell Script (GUI)
1. Open Task Scheduler
Open the Task Scheduler application from the Start Menu.
2. Create a New Task
> Right-click in the empty area and select Create Task.
> In the General tab, enter a name (e.g., DailyPSCollector
).
3. Set the Trigger
> Choose Daily and set the time to 8:05 AM (or your preferred schedule).
> Go to the Triggers tab and click New.
4. Define the Action
> Action: Start a program
> Program/script: powershell
> Arguments: -File “C:\temp\PowerShell_Scripts\avg_cpu_collector.ps1”
5. Review the Settings
> Click OK to save.
> Check the Settings tab for additional options like allowing the task to run on demand.
6. Verify Your Task
You’ll now see the task listed in the Task Scheduler main window.
More Tips for Automating PowerShell Scripts
> Use Proper Permissions: Run your scheduled tasks with a user account that has the necessary permissions.
> Test Your Script First: Before scheduling, run your PowerShell script manually to ensure it works as expected.
> Consider Logging: Add logging to your script to track its execution and troubleshoot any issues.
> Backup Your Tasks: Use PowerShell to export your scheduled tasks for backup or migration.