Schedule PowerShell script Archives - Office 365 Reports Generate Office 365 reports with PowerShell and stay informed about M365 news, tips, how-to's, and security best practices for efficient Microsoft 365 management. Fri, 15 Mar 2024 04:41:28 +0000 en-US hourly 1 /wp-content/uploads/2024/01/cropped-favicon-32x32.png?v=1705577855 Schedule PowerShell script Archives - Office 365 Reports 32 32 Modern Auth and Unattended Scripts in Exchange Online PowerShell V2  https://o365reports.com/2020/07/04/modern-auth-and-unattended-scripts-in-exchange-online-powershell-v2/?utm_source=rss&utm_medium=rss&utm_campaign=modern-auth-and-unattended-scripts-in-exchange-online-powershell-v2 https://o365reports.com/2020/07/04/modern-auth-and-unattended-scripts-in-exchange-online-powershell-v2/#respond Sat, 04 Jul 2020 13:04:35 +0000 http://o365reports.com/?p=2510 Usually, admins use the stored credential for unattended PowerShell scripts. With the introduction of security defaults and basic authentication deprecation, it’s necessary to adopt MFA for authentication. Since MFA requires users’ interaction to create Exchange session, people started to use Conditional Access policy to bypass MFA. But Conditional Access requires Azure AD Premium license.  So, most admins wanted a way to execute their PowerShell…

The post Modern Auth and Unattended Scripts in Exchange Online PowerShell V2  appeared first on Office 365 Reports.

]]>
Usually, admins use the stored credential for unattended PowerShell scripts. With the introduction of security defaults and basic authentication deprecation, it’s necessary to adopt MFA for authentication. Since MFA requires users’ interaction to create Exchange session, people started to use Conditional Access policy to bypass MFA. But Conditional Access requires Azure AD Premium license. 

So, most admins wanted a way to execute their PowerShell script with Modern auth and unattended authentication. 

After several months of waiting, Microsoft has released the EXO V2 preview module for non-interactive PowerShell scripts using Modern authentication.

 

Feb 2023 Update: Remote PowerShell (RPS) retirement in Exchange Online PowerShell

Due to RPS retirement, you can’t use EXO V1 and V2 modules to connect Exchange Online PowerShell. So admins must install/update to EXO V3 module to perform Exchange management tasks.

 

With the introduction of this new feature, 

    –You don’t need to exclude service accounts with Conditional Access policy. 

    –You don’t need to store credential in the local file 

    –You can easily automate script scheduler with Modern auth 

To automate Exchange Online PowerShell login, you need EXO V2 PowerShell module version 2.0.3 preview or later version. This unattended script authentication uses Azure AD applications, certificates, and Modern authentication. 

To install the EXO V2 module Preview release, run the below cmdlet. 

Install-Module -Name ExchangeOnlineManagement -RequiredVersion 2.0.3-Preview -AllowPrerelease

 

To update from an earlier version of EXO V2 module, run the below cmdlet. 

Update-Module -Name ExchangeOnlineManagement -AllowPrerelease

 

How to use the EXO V2 Module for Unattended Scripts? 

You can use Exchange Online PowerShell V2 module Preview to automate script scheduler with MFA/Modern authentication. 

The following examples show how to use the Exchange Online PowerShell V2 module with app-only authentication. 

Note: Administrators can create self-signed certificates and use them for internal and testing purposes, thereby avoiding the need for costly third-party Certificate Authority (CA) certificates

 

Connect to Exchange Online PowerShell using a local certificate: 

You need to use Connect-ExchangeOnline with CertificateFilePath and other necessary parameters. This method supports non-interactive scripts via Remote PowerShell using CertificateBased Authentication. 

Connect-ExchangeOnline -CertificateFilePath "C:\Users\admin\Desktop\automation-cert.pfx" -AppID "Testing App" -Organization "contoso.onmicrosoft.com"

 

Connect to Exchange Online PowerShell using certificate thumbprint: 

To use certificate thumbprint, you need to use Connect-ExchangeOnline with CertificateThumbPrint paramter. 

Connect-ExchangeOnline -CertificateThumbPrint "TESTINGTHUMBPRINT" -AppID "Testing Aoo" -Organization "contoso.onmicrosoft.com"

When you use the CertificateThumbPrint parameter, the certificate needs to be installed on the computer where you are running the command. The certificate should be installed in the user certificate store. 

 

Connect to Exchange Online PowerShell with existing service principal and client-secret: 

To connect Exchange online with existing service principal and client-secret, you need to follow the steps below.  

Step1: Get an OAuth access token using Active Directory Authentication Library (ADAL) PowerShell. 

Step 2: Create PSCredential object 

$AppCredential= New-Object System.Management.Automation.PSCredential(<UPN>,<Token>)

Step3: Pass the PSCredential to the EXO V2 module. 

Connect-ExchangeOnline -Credential $AppCredential

 

To setup app-only authentication, you can follow this Microsoft doc. 

This feature is valuable addition to the EXO V2 PowerShell module. It helps users to create non-interactive PowerShell scripts and connect to Exchange Online PowerShell with app-only authentication. Have you started upgrading existing PowerShell scripts to adopt this new method? Please share your experience with other admins and us. 

The post Modern Auth and Unattended Scripts in Exchange Online PowerShell V2  appeared first on Office 365 Reports.

]]>
https://o365reports.com/2020/07/04/modern-auth-and-unattended-scripts-in-exchange-online-powershell-v2/feed/ 0
How to Schedule PowerShell Script using Task Scheduler https://o365reports.com/2019/08/02/schedule-powershell-script-task-scheduler/?utm_source=rss&utm_medium=rss&utm_campaign=schedule-powershell-script-task-scheduler https://o365reports.com/2019/08/02/schedule-powershell-script-task-scheduler/#respond Fri, 02 Aug 2019 10:09:11 +0000 http://o365reports.com/?p=1470 PowerShell script reduces manually doing repetitive tasks. If you are frequently executing scripts at pre-defined times or specified time intervals, you may be tired of executing scripts repeatedly. Then, you can utilize Windows’ Task Scheduler to automate script execution for you. It will save your time and effort in executing…

The post How to Schedule PowerShell Script using Task Scheduler appeared first on Office 365 Reports.

]]>
PowerShell script reduces manually doing repetitive tasks. If you are frequently executing scripts at pre-defined times or specified time intervals, you may be tired of executing scripts repeatedly. Then, you can utilize Windows’ Task Scheduler to automate script execution for you. It will save your time and effort in executing script daily/weekly basis. Let’s see how to schedule PowerShell script through Task scheduler.

It can be done in two ways.

1.Schedule PowerShell script using Task Scheduler GUI

2.Schedule PowerShell script from Task Scheduler using PowerShell

 

Method 1: Schedule PowerShell Script using Task Scheduler

Open Task Scheduler (it can be found in the ‘Administrative tools’ or by pressing ‘Windows+R’ to open run and then type “taskschd.msc”.)

To run a script from Task Scheduler, follow these steps.

1.Open Task scheduler –> Task Scheduler Library –> Create Task

Schedule PowerShell script

2.In General tab, you can set scheduler name and description about the task like for what purpose the task has created.

Automate PowerShell script using Task Scheduler

Available security options explained below.

  • Specify the user on whose behalf the task will be run.
  • You can specify that a task should run . It can be done by selecting a radio button labeled ‘Run Whether the user is logged on not’. If this radio button selected, the task will not run interactively. To make a task run interactively, select the ’Run only when user is logged on’ radio button.
  • When the ‘Run whether user is logged on or not’ is selected, you may prompt to supply the credentials of the account, regardless of whether you select the checkbox ‘Do not store password’ or not. If the account is not logged on during task execution, saved credentials will be used.
  • If the task requires elevated privileges, then select the option ‘Run with highest privileges.’

3.Switch to the Trigger tab and click the New button. Here, you can set conditions that trigger a task.

Schedule PowerShell script using Task Scheduler

 

  • You can specify when to start the task. For example, you can have it executed on a schedule, at startup, at logon or whenever a particular event occurs by selecting ‘Begin the task’ drop-down menu.

Define time for Task scheduler

  • You can configure whether you want to run this task once or daily or weekly or monthly according to your scenario.
  • In the “Advanced settings”, you can choose to delay task, repeat task, stop task if it runs longer than the specified time period and expiry date.
    • Delay task for up to – This adds a random delay, so the task won’t stat at the exact time of the day.
    • Repeat task every – It shows the number of times a task should run after a trigger is fired.
      • Repeat task every – Time interval between each task repetition
      • For a duration of- How long a task should continue to repeat
    • Stop task if it runs longer than- If the task runs longer than the expected time or never quit, task will automatically stop if it reaches the mentioned time limit.
    • Expire – After the time period specified, the schedule won’t be triggered.

Automate PowerShell script

4.Then open the next tab ‘Actions’ and click the ‘New’ button.

Automate script

  • In the Action drop-down, “Start a program” is set by default. You can change it if required.
  • Using Browse, select program/script field. To schedule a script, we need to select powershell.exe.
    You can find powershell.exe in your system32\WindowsPowerShell\v1.0 folder.

c:\GetMFAStatus.ps1

If the path contains any blank space, it should be enclosed with quotes.

5.Once configured, you can specify conditions to determine whether the task should run. The task will not run if any condition specified here is not true.

Schedule PowerShell script through Task Scheduler

6.On the Settings tab, you can set additional advanced settings to control the task execution.

Run PowerShell script from Task Scheduler

Finally, click Ok to create a scheduled script.

Scheduled script will run as expected according to your schedule without any issue. If you want to check script execution, you can click Run by right-clicking task name.

schedule PowerShell script to run monthly

 

Automate PowerShell Script from Task Scheduler with Parameters

If you want to schedule the PowerShell script with parameters, use the below format.              

Script path -Param 1 Value1 -Param2 “Value 2”

For example, I am going to automate one of our PowerShell script: Export Office 365 Users MFA status report

During schedule, you can explicitly pass the credential as parameters as shown below:

C:\GetMFAStatus.ps1 -UserName "XXX XX" -Password ****

If the parameter value has blank space, values should be enclosed with quotes.

Note: If you want a more secure alternative to passing passwords as plain text, consider using certificates. Admins can easily create self-signed certificates for internal purposes, eliminating the need for expensive third-party CA certificates.

If you want to pass a switch parameter, you can use below syntax.

 C:\GetMFAStatus.ps1 -EnabledOnly

Above script exports Office 365 users MFA status whose MFA status is enabled. Here -EnabledOnly is a switch parameter.

Note: For cloud-based tasks, you can schedule scripts with Azure Automation, which allows you to monitor the execution history with enhanced visibility into failed jobs. This includes obtaining detailed error messages and outputs in the console for better analysis.

For more Office 365 related PowerShell scripts, you can refer O365Reports.com blog.

 

Method 2: Schedule PowerShell Script from Task Scheduler Using PowerShell

Instead of the detailed GUI approach to schedule PowerShell scripts, you can also employ PowerShell cmdlets to create a scheduled task. It involves the following steps: 

1.Define time for scheduler

2.Set Actions to be performed during execution

3.Save scheduler

 

Define Time for Scheduler:

New-SchdeuledTaskTrigger creates a scheduled task trigger object. Using this cmdlet, you can specify starting time of a task or starting a task multiple times on a daily or weekly basis.

$Time=New-ScheduledTaskTrigger -At 4.00PM -Once

Above cmd creates a scheduled task trigger that starts at 4PM and run once.

   $Time=New-ScheduledTaskTrigger -At 4.00PM -Daily -DaysInterval 2

Above cmd creates a scheduled task trigger that starts every 2 days at 4PM

 

Set Actions to be Performed During Execution:

New-SchdeuledTaskAction represent actions that executed when Task Scheduler runs the task. A task can have single action or a maximum of 32 actions. When you specify multiple actions, task Scheduler executes a task sequentially.      

$Action=New-ScheduledTaskAction -Execute PowerShell.exe -WorkingDirectory C:/Scripts -Argument “C:\Scripts\MFAStatus.ps1 -UserName XXXX -Password YYYY”

This command opens a PowerShell and change the directory to C:/Scripts and then invoke the MFAStatus.ps1 script.

 

Save Scheduler:

Register-ScheduledTask saves the scheduled task on a local computer.

Register-ScheduledTask -TaskName "Schedule MFA Status Report" -Trigger $Time -Action $Action -RunLevel Highest

The above cmd saves a scheduled task with a name “Schedule MFA Status Report” in the root folder. The saved task uses the pre-created action and trigger values that are specified by $Action and $Time variables.

 

Use Cases:

Using Task Scheduler, you can schedule a PowerShell script to run periodically. So that you don’t need to manually run a script on daily/Weekly/monthly basis. There are more scripts available on the internet which are scheduler friendly (Credentials can be passed as a parameter instead of saving inside the script). I have given some examples here.

In this blog, we have seen how to automate a PowerShell script using Task Scheduler.What’s your preferred approach when it comes to scheduling – GUI or PowerShell? Let us know in the comments section.

Also, if you need any enhancements like getting a scheduled report via email, or anything else, we’re all ears 🙂
We’ll carefully check your comments and work on bringing more sophistication to your requirements!

The post How to Schedule PowerShell Script using Task Scheduler appeared first on Office 365 Reports.

]]>
https://o365reports.com/2019/08/02/schedule-powershell-script-task-scheduler/feed/ 0