There are many reasons why you might want to run PowerShell scripts against Office 365/Exchange Online on a schedule, so I won’t fuss with any examples. Here is how it is done.
First you must create an encoded script file which contains the password for the Exchange Online/Office 365 admin which you want to use to login. It is important that you create the .key file
a) on the computer which will be running the scheduled task
b) using the account which will run the Scheduled Task
This is because as only the creator can decrypt the .key file, and this can only be done on the computer which generated the key file. To create your encrypted password file, open Powershell and run the following command:
Read-Host "Enter Password" -AsSecureString | ConvertFrom-SecureString | Out-File "C:\scripts\Password.txt"
This will ask you to enter the password and then give you a file full of rubbish. Now let’s do something with that rubbish! Your script to connect to Exchange Online and Office 365 should look like the following:
$TenantUname = "email@example.com" $TenantPass = cat "c:\scripts\password.key" | ConvertTo-SecureString $TenantCredentials = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $TenantUname, $TenantPass $msoExchangeURL = “https://ps.outlook.com/powershell/” $session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri $msoExchangeURL -Credential $TenantCredentials -Authentication Basic -AllowRedirection Import-PSSession $session Connect-MSOLService -Credential $TenantCredentials
After these lines, add in the Powershell commands you wish to run, or a reference to a script. Save this as a .ps1 file.
For example, Clutter can’t be disabled for the whole tenancy, so to get around this I might want to disable clutter for all my users every night by adding this line to the end of my script:
Get-Mailbox -ResultSize Unlimited | Set-Clutter -Enable $false
Once you are all done with your script, open Task Scheduler and create a new task.
On the general tab, ensure that the user account being used to run the task is the same account which created the password file, and make sure the ‘Run whether user is logged on or not’ is ticked. Add whichever time based triggers you need, and on the Actions page choose to ‘Start a Program’ with the following settings:
Add arguments: C:\Scripts\TestScript.ps1
Voila! You now have a script which uses an AES encrypted text file to connect to Exchange Online and Office 365 so that you can run your daily maintenance tasks from a single management server. Yay!