Quantcast
Channel: Hey, Scripting Guy! Blog
Viewing all articles
Browse latest Browse all 3333

Use PowerShell to Create Scheduled Tasks

$
0
0

Summary: Microsoft Scripting Guy, Ed Wilson, talks about using Windows PowerShell to create a scheduled task.

Microsoft Scripting Guy, Ed Wilson, is here. Today, it is cold, wet, and rainy—not exactly my favorite combination. In fact, I would rather have snow. At least then there would be an excuse for the dreariness. Oh well. Snow in the deep south is about as rare as—well...as rare as people who enjoy manually creating scheduled tasks.

Dude, creating scheduled tasks is boring. Not only that, it is easy to make a mistake. And when I am done creating a scheduled task, I am not really sure what it is going to do until it runs (or does not run) at the next scheduled time.

When I was consulting, I hated creating scheduled tasks because if I messed up, I had to drive across town to try to troubleshoot the thing. Often, my code was simply missing a comma, a quotation mark, or a space. Mistakes like that mean you cannot really bill the customer for it, which becomes a double whammy—the lost time and the lost billing. Luckily, with Windows PowerShell, it is much easier.

Note  The Scheduled Task module first appeared with Windows PowerShell 3.0 in Windows 8 and Windows Server 2012.

There are a few things that are required when it comes to creating a schedule task. One of these things is the action. What do I want the scheduled task to do? Without specifying an action, there is no reason to create a scheduled task.

Not only is this a requirement, but it can also be really frustrating. I need to get it exactly right. The graphical form can provide some clues. Here is the form for creating a new scheduled task action:

Image of menu

The action that I want is to start a program. In the New-ScheduledTaskAction cmdlet, this is the –Executeparameter, and I specify the name of the program I want to run. For me, that generally translates to PowerShell.exe. The Addarguments box translates to the –Argumentparameter. For me, this is everything I want to pass to the PowerShell.exe command. The Start in box translates to the –WorkingDirectory parameter of the cmdlet.

The hardest parameters to figure out are ­Execute and Argument. But I use the Run dialog box to see if I have my command working properly. Because the Run dialog box is not resizable (in fact, it doesn’t even scroll), it is frustrating to use.

So I type my commands in Notepad until I have something that works the way I want it to. Typing the command in Notepad provides me the chance to scroll and see exactly what I am typing, and it provides a convenient way for me to store my working command for later reference and reuse. In addition, by using Notepad, I can work with a long command and then use CTRL-A and CTRL-C to select and copy my command. I then use CTRL-V to paste it into the Run dialog box.

By directly executing my command line, I can fine tune the command easily and quickly. Following is the command I decided to use. (This is a single-line command that wraps in this post.)

Powershell -NoProfile -WindowStyle Hidden -command "& {get-eventlog -logname Application -After ((get-date).AddDays(-1)) | Export-Csv -Path c:\fso\applog.csv -Force -NoTypeInformation}"

I need to break-up the command for the Execute and Argument parameters. If I do not do this, when the scheduled task runs, an error message will pop up and ask me how I want to execute the program. Frustrating, but hey, not a biggie. Here is the command from my Windows PowerShell script:

$action = New-ScheduledTaskAction -Execute 'Powershell.exe' `

  -Argument '-NoProfile -WindowStyle Hidden -command "& {get-eventlog -logname Application -After ((get-date).AddDays(-1)) | Export-Csv -Path c:\fso\applog.csv -Force -NoTypeInformation}"'

Now I create a trigger. I want the command to run each day at 9:00 A.M. so that it will dump the previous day's events from the application log. To create the new trigger, I use the New-ScheduledTaskTrigger cmdlet:

$trigger =  New-ScheduledTaskTrigger -Daily -At 9am

One thing that is a bit confusing is that if I want my scheduled task to run, I need to register it. So, rather than using the New-ScheduledTask cmdlet, I use the Register-ScheduledTask cmdlet. I also provide it a name and a description, for example:

Register-ScheduledTask -Action $action -Trigger $trigger -TaskName "AppLog" -Description "Daily dump of Applog"

When I do this, it creates the new scheduled task, and it marks it as ready to execute. I can see it in the Task Scheduler GUI tool in the root folder. The task is shown here:

Image of menu

Following is the complete script:

$action = New-ScheduledTaskAction -Execute 'Powershell.exe' `

  -Argument '-NoProfile -WindowStyle Hidden -command "& {get-eventlog -logname Application -After ((get-date).AddDays(-1)) | Export-Csv -Path c:\fso\applog.csv -Force -NoTypeInformation}"'

$trigger =  New-ScheduledTaskTrigger -Daily -At 9am

Register-ScheduledTask -Action $action -Trigger $trigger -TaskName "AppLog" -Description "Daily dump of Applog"

Here are several things to keep in mind:

  • This script requires admin rights to create a new scheduled task.
  • The script will run in the context of the user who created the scheduled task.
  • The script uses absolute paths for the output CSV file.
  • The script overwrites all existing CSV files with the same name.
  • Be very careful with spaces in the argument portion of the script. It may look like it will work, but it might not if you press ENTER to break up the line of code.
  • The previous script is three lines of code, but I added a line break for the first line of code.

The script is shown here inside the Windows PowerShell ISE:

Image of command output

That is all there is to creating and registering a new scheduled task with Windows PowerShell. Scheduled Task Week will continue tomorrow when I will talk about more cool stuff.

I invite you to follow me on Twitter and Facebook. If you have any questions, send email to me at scripter@microsoft.com, or post your questions on the Official Scripting Guys Forum. See you tomorrow. Until then, peace.

Ed Wilson, Microsoft Scripting Guy


Viewing all articles
Browse latest Browse all 3333

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>