How To: Schedule PowerShell Script for an Exchange Task
This is commonly asked question, How to schedule a PowerShell script to run an Exchange task automatically? Here is the procedure to get it done.
Let’s take an example, I want to schedule a PowerShell script for auditing purpose, which scans whole environment & finds mailboxes which has some Send-As permission assigned and send the CSV formatted report to email id every Monday 9:00AM.
1. Set the PowerShell environment.
We need to set environment to run custom PS1 script which we created because by default PowerShell doesn’t allow to run it.
By default Execution Policy is ‘Restricted’ which means it does not load configuration files to run custom scripts. We need to change it to ‘RemoteSigned’ to run locally created PS1 scripts however RemoteSigned policy requires PowerShell script that may be downloaded must be signed.
This is one time activity so if you have already set the execution policy to RemoteSigned earlier then you can skip this step.
Run below command in ESM to set the execution policy.
2. Create a Script file (.PS1 file).
Here is the script to get the Send-As report in email.
Note: Change the FromAddress, ToAddress and ExchangeServerName in above script as per your environment if you are going to use same script.
It requires to add Exchange Management Snap-In to recognize Exchange CmdLets in PowerShell so make sure that below line is added into script.
You can refer below article for more detail about one liner cmdlet on getting a CSV formatted report of Send-As permissions assigned mailboxes.
3. Create a CMD/Bat file to execute the script.
Create a CMD/Bat file to execute PowerShell and pass the path of script with ‘-command’ switch.
4. Create a Schedule Task.
Create a schedule task and give the Bat file path to run. Set the password which has proper permission to execute the Exchange CmdLets available in script file.
Schedule this to run every week at specified time (9:00AM).
Well all things are set, now this mechanism runs every Monday 9:00AM and it will send a required report to mentioned email id.