RM Logo
Technical Rating: 
Support Home PageSupport
Print This PagePrint This Page
Add to 'My Library' Add to 'My Library'

How to automate a Windows PowerShell script to run against a Microsoft 365 domain
Published Date : 04 Nov 2014   Last Updated : 03 Oct 2024   Content Ref: TEC4194075  





Symptoms

As an administrator of Microsoft® 365™ you may want to schedule a Windows® PowerShell® script to run regularly against your Microsoft 365 domain. This article details how to achieve this by creating a scheduled task to automatically log on to Microsoft 365 and run a PowerShell script. It assumes you have a working PowerShell script or PowerShell commands that you can already run manually with success.


Requirements

You will need the following:

  • A server with Windows PowerShell v3 installed. Windows Server® 2012 has v3 by default but Windows Server 2008 does not.
  • Microsoft Azure™ Active Directory Module installed on the server: https://docs.microsoft.com/en-gb/powershell/module/Azuread/?view=azureadps-2.0.
  • A local or domain administrator account for the server.
  • PowerShell script containing the commands you want to run and which you can manually run with success in the Microsoft 365 domain.
  • Microsoft 365 global administrator credentials.


Procedure

Encrypt the Microsoft 365 administrator password
  1. As the logged on administrator, browse to My Documents (or Documents depending on your operating system).
  2. In the folder, create a new folder called WindowsPowerShell.
  3. In the WindowsPowerShell folder create a new blank file called creds.txt.
  4. In the PowerShell ISE window, click View, Show Script Pane to ensure you can see the script pane (top, white section) and the Command Prompt Console (bottom, blue section).
  5. Click View, 'Go to script pane'.
  6. Copy and paste the following into the script pane, changing admin@schooldomain.onmicrosoft.com to the global administrator account in your Microsoft 365 domain:


    $profilePath= (Join-Path (Split-Path $PROFILE) creds.txt)
    #2 Load current content
    try{
    $UnifyM365password = Get-Credential admin@schooldomain.onmicrosoft.com -ErrorAction Stop
    $UnifyM365password.password | ConvertFrom-SecureString | Set-Content $profilePath -ErrorAction Stop
    write-host 'Password updated'
    }
    catch{
    Write-Host 'Password File not updated'
    }

  7. From the toolbar, click 'Run script'.
  8. Enter the password for your Microsoft 365 administrator account when prompted.
  9. Confirm that you see 'Password updated' message in the console pane.

Automate Microsoft 365 log on in the PowerShell script
  1. In the PowerShell ISE window, click File, New to open a new blank tab.
  2. Click the new tab and in the script pane, open your PowerShell script or copy and paste the PowerShell commands you want to automate.
  3. Insert the following above your own PowerShell commands:

    $pwdloc=Join-Path (Split-Path $profile) creds.txt
    $M365password = gc $pwdloc
    $M365password = ConvertTo-SecureString $M365password -Force
    ##Import-Module Microsoft.Online.SharePoint.PowerShell -DisableNameChecking
    import-module msonline
    $M365username = 'admin@schooldomain.onmicrosoft.com'
    $M365credential = New-Object System.Management.Automation.PSCredential -ArgumentList $M365username,$M365password
    $sessionProxy = New-PSSessionOption -ProxyAccessType IEConfig -ea stop
    $Session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri https://ps.outlook.com/powershell/ -Credential $M365credential -Authentication Basic -AllowRedirection -SessionOption $sessionProxy -ea stop
    Import-PSSession $Session -AllowClobber -DisableNameChecking -ea stop
    Connect-MsolService -Credential $M365credential

  4. Adjust the script variables as necessary:
    • For $M365username = enter your global administrator account.
    • For -ProxyAccessType, use the appropriate value to match how the server connects to the Internet. For example, use -ProxyAccessType IEConfig if Windows Internet Explorer® has the correct proxy settings or use                        -ProxyAccesstype NoProxyServer if the server does not use a proxy server.
  5. Click Run from the toolbar to confirm the modified script runs successfully (typically this is signified by the console window returning to the PS C:\Windows\System32> prompt).
  6. Click File, Save As to save your script to a local location, e.g. C:\powershellscripts.

Schedule the automated script using Task Scheduler
  1. Open Administrative Tools, Task Scheduler.
  2. Create new task.
  3. Set to run as the administrator user you used above.
  4. Tick the 'Run whether user is logged on or not' box. 
  5. Click the Actions tab, then click New and browse to C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe.
  6. Click Open to populate the 'Program/script' field.
  7. In the 'Add arguments (optional)' field, type the path to the script you saved above,
    e.g. -executionpolicy bypass C:\powershellscripts\AssignProPlusLicence.ps1.
  8. In the 'Start in' field put the folder you saved the scripts to, e.g. C:\powershellscripts
  9. Click the Triggers tab, select New and set when you want the task to run.
  10. Consider whether you would like to configure the task to stop after running for a set period of time. 
  11. Click OK to finish.
  12. Check you have scheduled your task correctly by right-clicking and choosing Run.
  13. Enter your server administrator password when prompted. A result of 0x0 in the Task Scheduler window or logs will confirm that the task has completed successfully.


Checks

If you are new to scheduling and PowerShell scripting, please follow this process using a test PowerShell script that only updates a subset of users or test users, so you can check and confirm the desired results before going on to schedule a PowerShell script that updates a large number of users.


Possible Issues

Set the execution policy in PowerShell

If you cannot run your script manually in PowerShell, you may need to temporarily adjust your execution policy:

  1. Log on to the server with your administrator account.
  2. Open a Windows PowerShell ISE window.
  3. Click View, 'Go to console'.
  4. Type set-executionpolicy remotesigned and press Enter.

Error "cannot find module"

If you see an error "cannot find module" when manually running your script, check if you are running PowerShell as an administrator user and that the Microsoft Azure Active Directory module has been installed. You can type $env:psmodulepath in PowerShell to check the locations where the module should be, e.g. C:\Windows\System32\WindowsPowerShell\v1.0\Modules.



FEEDBACK
Did the information in this article help answer your question?
 Yes
 No
Please add any comments about this article in the box below. If you answered No then it is important you tell us why so that we can change the article if required. We can only respond if you log in to the RM Support website or provide your contact details. Note: If you need help with a technical query, please log a call online or telephone our support team.
Thank you for your feedback, which is sent directly to the RM Knowledge team. We address every message received with the intention of improving our Knowledge Library articles. If you have an unresolved technical issue, please contact RM Support.


If this article has not helped provide a solution then it is also possible to log a call...



Document Keywords: pro plus, power shell, a2, a3, o365, 365, office 365, scheduled, TEC4194075, m365


Please read - important disclaimer information.
http://www.rm.com/_RMVirtual/Includes/csredirect.asp?cref=&title=Standard Content Disclaimer


Top Of PageTop of page