In this comprehensive guide, I will take you through everything you need to know to manage Scheduled Tasks using PowerShell. From understanding the cmdlets to creating scheduled tasks, updating existing tasks, enabling-disabling scheduled tasks, and troubleshooting common issues, this guide covers it all.
Table of contents
- Introduction to Windows Task Scheduler and PowerShell cmdlets
- Understanding the benefits of using PowerShell scheduled tasks
- How to Create a Scheduled Task to Run a PowerShell Script?
- Creating a Scheduled Task using PowerShell Script: Step-by-Step
- Retrieving and listing scheduled tasks using PowerShell
- Editing a Scheduled Task using PowerShell
- Removing a Scheduled Task using PowerShell cmdlets
- Enabling and Disabling scheduled tasks with PowerShell
- Troubleshooting Scheduled Tasks in PowerShell
- Best Practices for PowerShell Scheduled Tasks
Introduction to Windows Task Scheduler and PowerShell cmdlets
Windows Task Scheduler is a built-in feature that allows you to schedule tasks to run automatically. You can use it to run scripts, launch applications, and perform other system-related tasks. PowerShell is a powerful scripting language that can be used to manage and automate Windows tasks. It provides a set of cmdlets that you can use to create, manage, and troubleshoot Scheduled Tasks.
As PowerShell is a scripting language, it comes as no surprise that you can automate the task-scheduling process using PowerShell scripts. This means that you can create scheduled tasks and manage them, saving you time and effort eventually. PowerShell Scheduled Tasks are a way to automate the execution of PowerShell scripts on a Windows Server or client machine. They can be set up to run at specific times, on certain days, or when certain events occur. This makes them an extremely powerful tool for automating routine tasks and freeing up your time for other things.
To get started with Scheduled Tasks, you need to understand the basic concepts behind them. There are a few key terms you should be familiar with:
- Task Scheduler: This is the built-in Windows tool that allows you to schedule tasks to run automatically.
- Task: A task is a specific action that you want to run at a specific time or event.
- Trigger: A trigger is a specific event that will cause a task to run.
- Action: An action is a specific task that you would like to run.
Understanding the benefits of using PowerShell scheduled tasks
Another major benefit of scheduled tasks is their flexibility. You can create tasks to run once, daily, weekly, monthly, or even at specific times throughout the day. This level of customization allows you to tailor the execution of your tasks to suit your specific needs. Additionally, through PowerShell, scheduled tasks can be easily managed and modified, giving you complete control over your automation processes.
Finally, it can be used to manage Scheduled Tasks on remote computers, which can be helpful in a network environment.
Real-World Examples to Spark Your Automation Journey
Here are some practical scenarios where scheduling PowerShell scripts with Task Scheduler can be a lifesaver:
- Automated System Backups: Schedule a script to run nightly, backing up critical system files to a secure location.
- Weekly Disk Cleanup: Set up a script to automatically clean up temporary files and optimize disk space on a weekly basis.
- Security Monitoring: Run a script periodically to check system logs for security events and send notifications if any suspicious activity is detected.
- SharePoint Online Management: For SharePoint Online administrators, leverage PowerShell scripts for automated tasks like user provisioning, permission management, or site creation. Schedule these scripts to run at specific intervals.
- Report Generation: Develop a PowerShell script to generate reports based on system data and schedule it to run daily or weekly. Then, deliver the reports to relevant stakeholders.
These are just a few examples to ignite your imagination. With PowerShell scripting and Task Scheduler, the possibilities for automation are virtually endless!
How to Create a Scheduled Task to Run a PowerShell Script?
- Open the Task Scheduler by typing “Task Scheduler” into the Start menu search bar and selecting the “Task Scheduler” app.
- Click “Create Task” in the “Actions” pane on the right-hand side.

- Give your task a name and description on the “General” tab.
- Configure your trigger on the “Triggers” tab. You can choose from a variety of trigger types, including “At startup,” “At logon,” “On a schedule,” and “On an event.”

- Configure your action on the “Actions” tab. Select “Start a program” and enter the path to your PowerShell script or executable.

- Click “OK” to save your task.
After setting up and configuring the scheduled task, you should test it to ensure that it’s working as expected. To do this, run the task and monitor the output. You can also view the task history and check whether any errors have occurred. If there are any issues, you can modify the task and rerun it. To create a scheduled task to run a PowerShell script, refer to: How to create a scheduled task with PowerShell to run a PowerShell script?
PowerShell provides a number of cmdlets that allow you to manage Scheduled Tasks from the command line. These cmdlets can be used to create, modify, and delete tasks, as well as to start and stop them.
The most important cmdlets for managing Scheduled Tasks in PowerShell are:
| Cmdlet | Description |
|---|---|
| New-ScheduledTaskTrigger | This cmdlet allows you to create a new trigger for a Scheduled Task. |
| New-ScheduledTaskAction | This cmdlet allows you to create a new action for a Scheduled Task. |
| Register-ScheduledTask | This cmdlet allows you to register a new Scheduled Task on the local machine. |
| Get-ScheduledTask | This cmdlet allows you to retrieve information about a Scheduled Task. |
| Set-ScheduledTask | This cmdlet allows you to modify an existing Scheduled Task settings. |
| Start-ScheduledTask | This cmdlet allows you to start a Scheduled Task manually. |
| Stop-ScheduledTask | This cmdlet allows you to stop a Scheduled Task manually. |
| Unregister-ScheduledTask | This cmdlet allows you to remove a Scheduled Task from the local machine. |
| Disable-ScheduledTask | Disables a scheduled task. |
| Enable-ScheduledTask | Enables a scheduled task. |
There are some more cmdlets available to manage scheduled tasks. See them at: https://learn.microsoft.com/en-us/powershell/module/scheduledtasks/?view=windowsserver2022-ps. Below are some examples of how you can create and manage scheduled tasks.
Creating a Scheduled Task using PowerShell Script
Step 1: Define the trigger
Use the New-ScheduledTaskTrigger cmdlet to create a new trigger for your task. This defines when the task should run. For example:
$Trigger = New-ScheduledTaskTrigger -Daily -At "6:00 AM"
This will create a trigger that runs your task every day at 6:00 AM.
Step 2: Set up the action to Run
After defining the trigger, you then need to define the action that the task should perform. Use the New-ScheduledTaskAction cmdlet to create a new action for your task. This can be used to call a PowerShell script or an executable file that performs the target action. In the case of a PowerShell script, you can pass arguments using the ‘Arguments’ parameter. For example, Here is the scheduled task action to run a PowerShell script:
$Action = New-ScheduledTaskAction -Execute "PowerShell" -Argument "C:\Scripts\SiteStorage.ps1"
This will create a new action that runs the specified PowerShell script.
Step 3: Create the Scheduled Task
Use the Register-ScheduledTask cmdlet to register your new task. For example:
Register-ScheduledTask -Action $Action -TaskName "Site Storage Report" -Trigger $Trigger
$Trigger = New-ScheduledTaskTrigger -Daily -At "6:00 am" $Action = New-ScheduledTaskAction -Execute "PowerShell" -Argument "C:\Scripts\SiteStorage.ps1" $Principal = New-ScheduledTaskPrincipal -UserId "NT AUTHORITY\SYSTEM" -LogonType ServiceAccount Register-ScheduledTask -TaskName "Site Storage Report" -Trigger $Trigger -Action $Action -Principal $Principal
This will register your new task with the name “Site Storage Report.” We have used variables for Trigger, action and Principal objects in the scheduled task. By customizing the trigger and action parameters, you can create scheduled tasks that suit your specific requirements. Once the task is created, it will be listed in the Task Scheduler, and it will run automatically according to the specified schedule.
Running scheduled tasks with the highest privileges using PowerShell
Register-ScheduledTask -TaskName "Site Storage Report" -Trigger $Trigger -Action $Action -RunLevel Highest
Retrieving and listing scheduled tasks using PowerShell
As your list of scheduled tasks grows, it becomes essential to have a way to retrieve and list them efficiently. PowerShell provides a range of commands that allow you to retrieve and filter scheduled tasks based on various criteria.
Get-ScheduledTask -TaskName "Site Storage Report"
This will display the details of the task with the specified name. If you want to list all the scheduled tasks in a specific folder, you can use the -TaskPath parameter:
Get-ScheduledTask -TaskPath "\MyFolder"
This will list all the tasks in the specified folder, regardless of their names. By combining various parameters and filters, you can retrieve and list scheduled tasks in a way that suits your needs.
Checking the Last Run Result of a Scheduled Task
To get the last run result of a scheduled task using PowerShell, you can leverage the Get-ScheduledTask and Get-ScheduledTaskInfo cmdlets. Here’s an example:
$Task = Get-ScheduledTask -TaskName "Site Storage Report" $TaskInfo = Get-ScheduledTaskInfo -InputObject $Task $TaskInfo.LastTaskResult
Editing a Scheduled Task using PowerShell
Once you have created a scheduled task, you may need to manage or modify it at some point. PowerShell provides a set of commands that allow you to perform various operations on existing scheduled tasks. To edit an existing PowerShell Scheduled Task using PowerShell cmdlets, you can use the Set-ScheduledTask cmdlet. For example:
# Change the description of a task Set-ScheduledTask -TaskName "Site Storage Report" -Description "Generate Report at every Monday" # Update the trigger of a task $Trigger = New-ScheduledTaskTrigger -Weekly -DaysOfWeek "Monday" Set-ScheduledTask -TaskName "Site Storage Report" -Trigger $Trigger
This will modify the “Site Storage Report” task to use the new trigger and action. You can also use the Set-ScheduledTask cmdlet to modify specific properties of a task, such as a trigger or action. For example, you want to modify the time the task runs at. First, get the task and trigger, then modify the properties, and finally update the task using Set-ScheduledTask.
$Task = Get-ScheduledTask -TaskName "Site Storage Report"
$Task.Triggers[0].StartBoundary = (Get-Date "9:00 AM").ToString("s")
$Task | Set-ScheduledTaskThis script changes the run time of the task “Site Storage Report” to 9:00 AM.
Starting and stopping scheduled tasks with PowerShell
Once you have created a scheduled task, you may need to manually start or stop it at times. PowerShell provides commands that allow you to start, stop, and run scheduled tasks with ease.
Start-ScheduledTask -TaskName "Site Storage Report"
This will initiate the execution of the task according to its defined schedule or trigger. Similarly, if you want to stop the execution of a running task, you can use the Stop-ScheduledTask cmdlet. This command terminates the execution of the specified task.
Stop-ScheduledTask -TaskName "Site Storage Report"
This will stop the execution of the task, regardless of its current state. By using these commands, you can have full control over the execution of your scheduled tasks.
Removing a Scheduled Task using PowerShell cmdlets
# Delete scheduled task powershell Unregister-ScheduledTask -TaskName "Site Storage Report" -Confirm:$false
This will remove the “Site Storage Report” task without asking for confirmation. It’s important to note that removing a task is irreversible, so make sure you double-check before executing the command.
Enabling and Disabling scheduled tasks with PowerShell
In some cases, you may need to temporarily disable a scheduled task without removing it completely. PowerShell provides commands that allow you to disable and enable scheduled tasks with ease.
Disable-ScheduledTask -TaskName "Site Storage Report"
This will temporarily disable the task, allowing you to make changes or troubleshoot any issues without the task running in the background. If you want to enable a disabled task, you can use the Enable-ScheduledTask cmdlet:
Enable-ScheduledTask -TaskName "Site Storage Report"
This will reactivate the task, allowing it to run according to its defined schedule or trigger. By using these commands, you can easily control the state of your scheduled tasks.
Troubleshooting Scheduled Tasks in PowerShell
While PowerShell scheduled tasks are a powerful tool, they can occasionally encounter issues. Troubleshooting Scheduled Tasks in PowerShell can be challenging, especially if the tasks are not running as expected. Some common issues include: Tasks not running as expected, tasks not being created or modified correctly, or tasks failing to execute due to permissions or resource conflicts. If you’re having issues with a Scheduled Task, there are a few things you can do to troubleshoot the problem:
- Incorrect task properties, such as the start time or the repetition interval
- Incorrect user credentials or permissions
- Incorrect script syntax or execution policy
- Conflicts with other tasks or applications
- Resource limitations, such as disk space or memory
To troubleshoot these issues, you can use several PowerShell techniques, such as:
- Using the Get-ScheduledTaskInfo cmdlet to retrieve task information and status
- Check the history of the task to see if it has been running successfully.
- Using the Event Viewer to retrieve system and application logs
- Using the PowerShell ISE to step through the script execution
Best Practices for PowerShell Scheduled Tasks
- Use descriptive task names and descriptions to identify the tasks
- Use strong passwords and least privileged accounts to run the tasks
- Use error handling and logging to troubleshoot issues
- Use version control and backups to manage the task scripts and configurations
- Use testing and staging environments to test the tasks before deploying them to production
- Use security policies and firewalls to protect the tasks and the computer from external threats
- Use the
-ExecutionPolicy Bypassswitch when running your scripts to ensure that they can run without issues.
Conclusion
In this article, I’ve shown you how to create and manage Scheduled Tasks on Windows using PowerShell. I’ve explained the benefits of using PowerShell for Scheduled Tasks and provided examples of PowerShell cmdlets for creating, managing, and troubleshooting tasks. I’ve also shown you PowerShell scripts and best practices for managing Scheduled Tasks more efficiently.
With the proper steps and cmdlets, you can set up tasks that complete critical tasks like backups, system maintenance, and data validation, among others. With this comprehensive guide, you have all the information you need to start maximizing your efficiency with PowerShell Scheduled Tasks.
To schedule and execute a PowerShell script from Windows Task scheduler, refer to: How to Run a PowerShell Script using Windows Task Scheduler?
How can I retrieve information about existing scheduled tasks using PowerShell?
You can use the Get-ScheduledTask cmdlet to retrieve information about existing scheduled tasks. For example, to retrieve all scheduled tasks, you can run: Get-ScheduledTask. To retrieve a specific scheduled task by name, you can use: Get-ScheduledTask -TaskName "MyTask"
What is Task Scheduler in the context of PowerShell?
Can I run a scheduled task manually using PowerShell?
Yes, you can use the Start-ScheduledTask cmdlet to run a scheduled task manually. For example: Start-ScheduledTask -TaskName "MyTask"
Can I schedule a PowerShell script to run periodically using Task Scheduler?
Yes, using Task Scheduler, you can schedule a PowerShell script to run periodically, eliminating the need to manually run a script on a daily, weekly, or monthly basis.
How can I export and import scheduled tasks using PowerShell?
Can I create a Scheduled Task to run when the computer starts?
Yes, you can set a trigger for your task to run at startup using the New-ScheduledTaskTrigger cmdlet with the -AtStartup parameter.
How do I set up a Scheduled Task to run with the highest privileges?
When registering the task, use the -RunLevel Highest parameter with the Register-ScheduledTask cmdlet to run the task with the highest privileges.
PowerShell scripts are a great way to automate daily tasks or generate weekly reports. But how do you make a scheduled task for your PowerShell scripts? We can do this with either the task scheduler to run a PowerShell script or create the task in PowerShell.
The advantage of scheduled tasks is that you can set and forget them. They will run in the background, and update your systems, or generate the reports that you otherwise will have to do manually.
In this article
In this article, we will look at how to run a PowerShell script with task scheduler and how to create a scheduled task in PowerShell.
Use Task Scheduler to Run a PowerShell Script
The first option that we are going to look at is using the task scheduler in Windows to run a PowerShell Script. The Windows Task Scheduler originates from Windows 95! and is a great way to schedule tasks in Windows.
To run PowerShell scripts with the task scheduler, we can’t simply select the PowerShell file that we want to schedule. What we are going to do is run the “program” PowerShell and use the arguments to select the file that we want to run.
2 minutes
- Open Task Scheduler
- Create a new basic task

- Schedule the task
The trigger determines when the task should be executed. Choose a trigger, for example, Weekly, and click Next to configure when exactly the tasks need to be executed.
- Set the Action
Here comes the important part, for the action, we are going to Start a Program

- Start a Program – PowerShell
The program that we want to run is PowerShell. Just enter PowerShell in the Program/Script field (see screenshot in step 6), you don’t need to find the exact path to the executable.
- Add Arguments
In the arguments field, we are going to add the argument
-Fileand path to the PowerShell script. It’s also a good idea to add the PowerShell switch-NoProfileand set the-ExecutionPolicyto ByPass.If your scripts require any parameters then you can add them after the path (for example the -Output parameter):
-NoProfile -ExecutionPolicy Bypass -File "C:\scripts\ADHealth.ps1" -Output "HTML"
- Start in
Always set the Start in location to the same path as where your script is located. This way any exports that your script generates will be stored in the same location as your script. Otherwise, the output will be saved in C:\Windows\System32
- Finish

- Advanced Settings
There are two settings that we need to change for our scheduled PowerShell task. We will need to make sure that the script runs even when we are not logged on, which you do on the General tab.

- Save the task
Click Ok and enter your password, so the task can run when you are not logged on. It is always a good idea to test your task, right-click on it, and choose Run to run the task now.
We can of course also use PowerShell to create and manage scheduled tasks. Creating a scheduled task in PowerShell requires a couple of steps. For each step, there is a different cmdlet that we are going to use.
| Cmdlet | Description |
|---|---|
| New-ScheduledTaskTrigger | Creates a trigger object for a scheduled task |
| New-ScheduledTaskAction | Creates the action for a scheduled task |
| Register-ScheduledTask | Registers a scheduled task |
| Get-ScheduledTask | Show the scheduled tasks |
$taskTrigger = New-ScheduledTaskTrigger -Weekly -DaysOfWeek Friday -At 3am $taskAction = New-ScheduledTaskAction -Execute "PowerShell" -Argument "-NoProfile -ExecutionPolicy Bypass -File 'C:\scripts\ADHealth.ps1' -Output 'HTML'" -WorkingDirectory 'c:\scripts' Register-ScheduledTask 'Lazy PS Tasks' -Action $taskAction -Trigger $taskTrigger
This will create the exact same task that we have created with the task scheduler. But let’s explain each of the cmdlets to see what options we have.
Creating the Trigger – New-ScheduledTaskTrigger
The first step is to define the trigger. This determines when we want to run the task. Just like with the task scheduler, we can define multiple triggers for our task.
The New-ScheduledTaskTrigger cmdlet comes with a couple of parameters that allow you to define when you want to task to run:
- AtLogOn – Runs the task when a user logs on
- AtStartup – When the system is started
- At – Used with Once, Daily, or Weekly. Defines the specific time to run the task
- Daily – Runs every day. Define the days with DaysOfWeek
- DaysInterval – Run every x days
- DaysOfWeek – This can be used with Daily or Weekly. Defines which days to run the task
- Weekly – Runs the tasks every week
- WeeklyInterval – Determines the interval between the weeks.
$trigger = New-ScheduledTaskTrigger -Weekly -DaysOfWeek Tuesday,Thursday -At 8:30am
Defining the Action – New-ScheduledTaskAction
To create the scheduled task action in PowerShell we will need to define which program we want it to run, any arguments (the path to the PowerShell scripts for example), and optionally the working directory.
So to run our PowerShell script we will set the -Execute parameter to PowerShell and define the file path and other parameters in the -Argument parameter. If your scripts require it, you can set the –WorkingDirectory parameter to the path of your script
$action = New-ScheduledTaskAction -Execute 'PowerShell' -Argument '-NoProfile -ExecutionPolicy Bypass -File "C:\scripts\ADHealth.ps1" -Output "HTML"'
Creating the Task – Register-ScheduledTask
With the trigger and action defined, we can create and register the scheduled task. We will need to give our task a name and I recommend adding a TaskPath (folder) as well. This will make it easier to retrieve your tasks later on.
Register-ScheduledTask -TaskName 'Lazy PS Tasks' -TaskPath 'LazyTasks' -Action $taskAction -Trigger $taskTrigger

As mentioned you can define multiple triggers and actions for your task. To do this you will need to add the trigger or actions in an array. For example, to run the task every Tuesday and Thursday and on the first day of the month we can do:
# Define the triggers for Tuesday and Thursday at 08:30 AM and when a user logs on $taskTriggers = @( New-ScheduledTaskTrigger -Weekly -DaysOfWeek Tuesday,Thursday -At 08:30, New-ScheduledTaskTrigger -AtLogon ) Register-ScheduledTask -TaskName 'Lazy PS Tasks' -TaskPath 'LazyTasks' -Action $taskAction -Trigger $taskTriggers
Running the Task with Different Privileges
Register-ScheduledTask -TaskName "Lazy PowerShell Tasks" -taskPath 'LazyTasks' -Action $taskAction -Trigger $taskTrigger -User "lazyadmin\Administrator" -Password 'yourPass123' -RunLevel Highest
View the Scheduled Task
You can view your created tasks in the task scheduler. But you can also retrieve the scheduled task with PowerShell. For this, we will need to use the cmdlet Get-ScheduledTask. If you run the cmdlet without any parameters, then it will retrieve all scheduled tasks on your computer.
And as you can see, that is quite a lot. That’s why it’s important to organize your tasks in folders by using the taskPath parameter. This way you can use the TaskPath parameter to view only our tasks:
Get-ScheduledTask -TaskPath \LazyTasks\
The task path always starts and ends with a backslash \. To view your tasks you will need to supply the TaskName. If the name is unique, then the name alone will be enough. Otherwise, you will need to supply the path as well:
Get-ScheduledTask -TaskName 'Lazy PS Tasks' -TaskPath \LazyTasks\ | Select *
As you can see in the screenshot above, we can’t see all the details of the task. To view the Actions or Triggers we will need to expand the properties. We can do this by using the ExpandProperty method or by saving the results in a variable:
Get-ScheduledTask -TaskName 'Lazy PS Tasks' -TaskPath \LazyTasks\ | Select -ExpandProperty Triggers # Or $task = Get-ScheduledTask -TaskName 'Lazy PS Tasks' -TaskPath \LazyTasks\ $task.Triggers
Updating Tasks
To update scheduled tasks with PowerShell you can use the Set-ScheduledTask cmdlet. It works similar to the Register-ScheduledTask cmdlet. Just create a new trigger or action first and then add it just like when you would create it.
# Define new trigger $newTrigger= New-ScheduledTaskTrigger -Weekly -DaysOfWeek Monday -At 08:30 # Update the task Set-ScheduledTask -TaskName "Lazy PowerShell Tasks" -taskPath 'LazyTasks'-Trigger $newTrigger
Wrapping Up
Scheduling PowerShell Tasks can be done with both Task Scheduler and in PowerShell with the Register-ScheduledTask cmdlet. Personally, I find it easier to create the task using PowerShell, but to modify it, I find the task scheduler more convenient.
Nevertheless, you can use both options to schedule your PowerShell scripts. I hope you found this article helpful, if you have any questions, just drop a comment below.
Key takeaways
- PowerShell efficiency: The script showcases the efficiency of PowerShell in managing scheduled tasks on Windows systems.
- Enhanced task management: Offers detailed insights into scheduled tasks, surpassing traditional GUI methods.
- Flexible parameters: Includes options to filter tasks by Microsoft origin and disabled status.
- Administrative access requirement: Requires running with administrative privileges for full functionality.
- Customizable output: Provides options to output task information to the host or save to a custom field.
- Security and compliance: Assists in auditing tasks for security and compliance purposes.
- Automated reporting: Simplifies the process of generating reports on scheduled tasks.
- NinjaOne integration: Highlights the script’s compatibility and enhanced functionality with NinjaOne’s IT management tools.
- Broad compatibility: Compatible with Windows 10 and Windows Server 2012 R2 and later versions.
- Best practices: Emphasizes the importance of regular audits and careful management of output data for security.
Background
This PowerShell script is designed for IT professionals and Managed Service Providers (MSPs) who require an efficient way to retrieve and manage scheduled tasks on Windows systems. The ability to list, analyze, and optionally modify scheduled tasks is crucial for maintaining system health, security, and performance. This script addresses these needs by offering a detailed overview of scheduled tasks, with options to include or exclude tasks based on specific criteria.
The script:
<#
.SYNOPSIS Retrieves a list of scheduled tasks and outputs the list into the activity log. This list can optionally be saved to a Custom Field.
.DESCRIPTION Retrieves a list of scheduled tasks and outputs the list into the activity log. This list can optionally be saved to a Custom Field.
.EXAMPLE (No Parameters) Scheduled Task(s) Found! TaskName TaskPath State -------- -------- ----- Firefox Background Update 3080... \Mozilla\ Ready
PARAMETER: -IncludeMicrosoft Includes Scheduled Tasks created by Microsoft in the report.
PARAMETER: -IncludeDisabled Includes Scheduled Tasks that are currently disabled in the report.
PARAMETER: -CustomFieldName "ReplaceMeWithAnyMultilineCustomField" Name of a multiline custom field to save the results to. This is optional; results will also output to the activity log.
.OUTPUTS None
.NOTES Minimum OS Architecture Supported: Windows 10, Windows Server 2012 R2 Release Notes: Initial Release
By using this script, you indicate your acceptance of the following legal terms as well as our Terms of Use at https://www.ninjaone.com/terms-of-use. Ownership Rights: NinjaOne owns and will continue to own all right, title, and interest in and to the script (including the copyright). NinjaOne is giving you a limited license to use the script in accordance with these legal terms. Use Limitation: You may only use the script for your legitimate personal or internal business purposes, and you may not share the script with another party. Republication Prohibition: Under no circumstances are you permitted to re-publish the script in any script library or website belonging to or under the control of any other software provider. Warranty Disclaimer: The script is provided “as is” and “as available”, without warranty of any kind. NinjaOne makes no promise or guarantee that the script will be free from defects or that it will meet your specific needs or expectations. Assumption of Risk: Your use of the script is at your own risk. You acknowledge that there are certain inherent risks in using the script, and you understand and assume each of those risks. Waiver and Release: You will not hold NinjaOne responsible for any adverse or unintended consequences resulting from your use of the script, and you waive any legal or equitable rights or remedies you may have against NinjaOne relating to your use of the script. EULA: If you are a NinjaOne customer, your use of the script is subject to the End User License Agreement applicable to you (EULA).
#>
[CmdletBinding()]
param ( [Parameter()] [Switch]$IncludeMicrosoft = [System.Convert]::ToBoolean($env:includeMicrosoftTasks), [Parameter()] [Switch]$IncludeDisabled = [System.Convert]::ToBoolean($env:includeDisabledTasks), [Parameter()] [String]$CustomFieldName
)
begin { # Get CustomFieldName value from Dynamic Script Form. if ($env:customFieldName -and $env:customFieldName -notlike "null" ) { $CustomFieldName = $env:customFieldName } # Some Scheduled Tasks require Local Admin Privileges to view. function Test-IsElevated { $id = [System.Security.Principal.WindowsIdentity]::GetCurrent() $p = New-Object System.Security.Principal.WindowsPrincipal($id) $p.IsInRole([System.Security.Principal.WindowsBuiltInRole]::Administrator) } # Initialize Generic List for Report $Report = New-Object System.Collections.Generic.List[String]
}
process { if (-not (Test-IsElevated)) { Write-Error -Message "Access Denied. Please run with Administrator privileges." -Category PermissionDenied -Exception (New-Object -TypeName System.UnauthorizedAccessException) exit 1 } # By default, we'll exclude tasks made by Microsoft. They don't always put themselves down as an author. if (-not $IncludeMicrosoft) { $ScheduledTasks = Get-ScheduledTask | Where-Object { $_.Author -notlike "Microsoft*" -and $_.TaskPath -notlike "\Microsoft*" } } else { $ScheduledTasks = Get-ScheduledTask } # We should ignore disabled tasks unless told otherwise. if (-not $IncludeDisabled) { $ScheduledTasks = $ScheduledTasks | Where-Object { $_.State -notlike "Disabled" } } # The activity log isn't going to fit all this output, so we'll trim it if it's too large. if ($ScheduledTasks) { $FormattedTasks = $ScheduledTasks | ForEach-Object { $Name = if (($_.TaskName).Length -gt 30) { ($_.TaskName).Substring(0, 30) + "..." }else { $_.TaskName } $Path = if (($_.TaskPath).Length -gt 30) { ($_.TaskPath).Substring(0, 30) + "..." }else { $_.TaskPath } [PSCustomObject]@{ TaskName = $Name TaskPath = $Path State = $_.State } } Write-Host "Scheduled Task(s) Found!" $Report.Add(( $FormattedTasks | Format-Table TaskName, TaskPath, State -AutoSize | Out-String )) } else { $Report.Add("No Scheduled Tasks have been found.") } # Output our results. Write-Host $Report # Save our results to a custom field. if ($CustomFieldName) { Ninja-Property-Set -Name $CustomFieldName -Value $Report }
}
end {
}Access 300+ scripts in the NinjaOne Dojo
Detailed breakdown
The script begins with a CmdletBinding declaration, allowing it to be used as a PowerShell cmdlet with various parameters. These parameters include flags to include Microsoft and disabled tasks, and an option to save output to a custom field.
Potential use cases
Comparisons
Traditional methods of managing scheduled tasks often involve manual checks or using the Windows Task Scheduler GUI. This script, however, automates the process and provides more flexibility, especially in environments with numerous servers.
FAQs
- Can this script run on any Windows version?
- It supports Windows 10 and Windows Server 2012 R2 onwards.
- Is it necessary to run the script with admin privileges? –
- Yes, for complete access to all tasks.
- Can the script output be customized? –
- Yes, through the $CustomFieldName parameter.
Implications
Recommendations
- Always run the script with administrative privileges for a complete overview.
- Regularly audit scheduled tasks, especially in environments with frequent changes.
- Use the custom field output option for detailed reporting and analysis.
Final thoughts
In an era where automation and security are paramount, this PowerShell script stands as a testament to the capabilities of tools like NinjaOne. NinjaOne can further streamline these processes, integrating seamlessly with scripts like this to provide comprehensive IT management solutions. By leveraging such scripts, IT professionals can not only ensure efficient operations but also bolster their security posture, a necessity in today’s rapidly evolving digital landscape.


