Thursday, April 28, 2011

Schedule your Exchange 2010 scripts

If you’re running Exchange you most likely want to run script on a regular basis.

Here is how you schedule a Exchange 2010 management shell script.

Copy your script file into a folder of your choice. ex. c:\script\script.ps1

The most tricky part is how to actually start the powershell script to run. This is set on the actions tab.
Create new action with “start a program” and for program/script enter the path to powershell.exe
%SystemRoot%\system32\WindowsPowerShell\v1.0\powershell.exe

for the argument textbox, enter
-Command “. 'C:\Program Files\Microsoft\Exchange Server\V14\bin\RemoteExchange.ps1'; Connect-ExchangeServer -auto; C:\script\script.ps1”

The RemoteExchange.ps1 is the script that start a remote Exchange 2010 Management shell session to an Exchange 2010 server. The last part is the path to your script.

Several settings on the job depends on what your script does.
You might need to run the script highest privileges, Configure for Windows 7, Windows Server 2008 R2 etc.

If you know that your script normally take 5 min to run, it’s a good practice to use settings to either stop if it runs for a long time and also block multiple instances to run at the same time.

Another handy thing you can include in your script is actually to make the Exchange snapin to load from the script instead of having the task load it.
Here is an example.

# some Exchange script
# bla bla.

# Load the Exchange snapin if it's no already present.
function LoadExchangeSnapin
{
if (! (Get-PSSnapin Microsoft.Exchange.Management.PowerShell.E2010 -ErrorAction:SilentlyContinue) )
{
Add-PSSnapin Microsoft.Exchange.Management.PowerShell.E2010 -ErrorAction:Stop
}
}


# The meat of the script!
&{

"*** some Exchange Script started ***" >> scriptlogfile.log
[DateTime]::Now >> scriptlogfile.log

# Load the Exchange cmdlets.
& LoadExchangeSnapin

# the rest of the script

[DateTime]::Now >> scriptlogfile.log
"*** some Exchange Script ended ***" >> scriptlogfile.log
}


2 comments:

  1. Hi,
    When I schedule the script it runs fine under the "currently logged on user" but fails if I assign Local System. How can I specify the user id and password (of exchange admin) to be used while running the script.
    Thanks
    MF

    ReplyDelete
  2. You cannot run use Local System when running your Exchange script, it must be a user account since the local system don't have any permission in Exchange.
    On the General tab of the scheduled task properties, there is a button "change user or group". Select a user with appropriate Exchange permission to accomplish what your script try to do.

    ReplyDelete