Contents

Scheduled Tasks - PowerShell Scripts with Parameters


Contents

Perhaps a very “simple” issue, but I noticed that when looking for this it took me longer than expected to find the result I had in mind.

The issue at hand

I  have a script which requires various parameters to be provided so that I can run it. When running the command through an active console session it would look like this:

1
.\Get-MailboxAuditLoggingReport.ps1 -Mailbox ProblemMailbox -Hours 24 -SendEmail -MailFrom administrator@contoso.com -MailTo administrator@contoso.com -MailServer mail.contoso.com

As you can see, this can be quite the pain,  but if I get this configured properly can re-use this at various customers.

The solution

Now I won’t bore you with all the Scheduled Tasks Wizard screen, as there is only 1 screen that’s important for all of this: The Start a Program screen

What you need to fill in to make sure you get PowerShell to run the script you require, using the parameters you want it to use.

  • Program/Script Full path to PowerShell executable [while some people have gotten it to work with just PowerShell, this should ALWAYS work]

    ```powershell C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe
1
2
3
4


  * <span style="text-decoration: underline;"><strong>Add arguments (optional)</strong></span> ```powershell
-Command "& &lt;full script path&gt; &lt;parameters + values&gt;"
for example

```powershell

-Command “& C:\Scripts\Get-MailboxAuditLoggingReport.ps1 -Mailbox ProblemMailbox -Hours 24 -SendEmail -MailFrom administrator@contoso.com -MailTo administrator@contoso.com -MailServer mail.contoso.com”

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15


  * **<span style="text-decoration: underline;">Start in (optional)</span>
** Not required

That's it!

# Extra Tip

While this should be all that's required to make sure it runs properly, I found a tip that might prove quite useful when troubleshooting issues with Scheduled Tasks:

In the **Add arguments (optional)** section, if you add

```powershell
; exit $LASTEXITCODE

after your full script path + parameters, it will properly include the last exit code under the Last Run Results column, making troubleshooting that much easier.

Happy scripting 🙂