Powershell script to run automated tasks for O365 using stored credentials

 

Since i started working on office 365 ,have been getting many requests to automate some of the repetitive tasks such as o365 license report ,Off boarding process (when employee leave the company) ,enable MFA (this can be done using CA as well without script based), Get the MFA status for users etc and many other on intune related as well.

For All these scripts that we run from On-Prem(Trusted locations) ,i always find difficult to enter tenant ID and password every time when i run the script ,hence i have decided to supress the credential prompts and let script run without any manual intervention.

If you have enabled MFA for account that you use to run the scripts ,this method doesn't work.

we have MFA enabled for all the accounts but we define conditional access to supress MFA if user logged in from trusted location which is on-prem.

Below is the few liner code to store your credentials on encrypted format for the tenant user name and use this file to run the script in automated way using schedule tasks .

I strongly suggest to have access to the encrypted file for selected users on the PC that you place it on.

In this blog post, I will go with simple PowerShell script that will generate list users with their o365 license information and output into CSV file.

First decide location to store the encrypted file that store password ( I place it on server in D:\sources\scripts\PW.key)

We start with storing the password for the user name (tenant user name i.e eswar@eskonr.com is the user name who is Global administrator).

Read-Host -Prompt "Enter your tenant password" -AsSecureString | ConvertFrom-SecureString | Out-File "D:\sources\scripts\PW.key"

image

Once the password is entered, it store in PW.Key file. This is onetime task until the password for the tenant user changed .If you park accounts in cyberark, you might have to rerun the above command line so frequently.

Now ,we can use this file to run our scripts on o365 tenant.

I will now start with getting the script location as current directory to store the output file with today’s date.

$scriptPath = $script:MyInvocation.MyCommand.Path
$dir = Split-Path $scriptpath
$date = (get-date -f dd-MM-yyyy-hhmmss)

Next to import the required module

try {
    Import-Module -Name MSOnline -ErrorAction Stop
    }
catch {
       Write-Warning -Message "Failed to import module"
      }

Next is to define the tenant user name and tenant password file that we encrypted and later start running actual script.

$TenantUname = "eswar@eskonr5.com"
$TenantPass = cat "D:\sources\scripts\PW.key" | ConvertTo-SecureString
$TenantCredentials = new-object -typename System.Management.Automation.PSCredential -argumentlist $TenantUname, $TenantPass

Finally we try to run the actual script that bring the results from o365.

Connect-MsolService -Credential $TenantCredentials
Get-MsolUser -All |Where {$_.IsLicensed -eq $true } |Select DisplayName,SigninName,Title,Department,UsageLocation,@{n="Licenses Type";e={$_.Licenses.AccountSKUid}} | Export-Csv -Path "$dir\O365UserLicenseInfo-$date.csv"  -NoTypeInformation

Full script is given below:

image

<#
Title:Get o365 user license information
Author:Eswar Koneti
Date:19-Feb-2018
#>

#Read-Host -Prompt "Enter your tenant password" -AsSecureString | ConvertFrom-SecureString | Out-File "D:\sources\scripts\PW.key"
#Get the script location path
$scriptPath = $script:MyInvocation.MyCommand.Path
$dir = Split-Path $scriptpath
$date = (get-date -f dd-MM-yyyy-hhmmss)

# Import required modules
try {
    Import-Module -Name MSOnline -ErrorAction Stop
    }
catch {
       Write-Warning -Message "Failed to import module"
      }
#Define tenant user details and to match with the password you entered above
$TenantUname = "eswar@eskonr5.com"
$TenantPass = cat "D:\sources\scripts\PW.key" | ConvertTo-SecureString
$TenantCredentials = new-object -typename System.Management.Automation.PSCredential -argumentlist $TenantUname, $TenantPass

Connect-MsolService -Credential $TenantCredentials
Get-MsolUser -All |Where {$_.IsLicensed -eq $true } |Select DisplayName,SigninName,Title,Department,UsageLocation,@{n="Licenses Type";e={$_.Licenses.AccountSKUid}} | Export-Csv -Path "$dir\O365UserLicenseInfo-$date.csv"  -NoTypeInformation

 

Hope it helps!

3 Responses to "Powershell script to run automated tasks for O365 using stored credentials"

  1. Nlemuscruz19 Lemus · Edit

    Hola, pregunta..

    este script esta genial y funciona.

    Pero en algun momento dejo de funcionar en una maquina unida al dominio. pero en una red externa funciona el script.

    En este caso que puertos de red y url necesita por si se esta bloqueando estos?

    Reply
  2. Hi Eswar,

    What you have posted here is brilliant. And thank you for that.

    I have a specific requirement that I want to achieve with an automated solution. Hope you will have some answer for this as you seems to be very experienced here.

    I work for a school in the UK where we have users with TITLE of 'Teaching Staff' and 'Non-Teaching-Staff''

    And we have AA Groups to send email as 'AA Teaching Staff' and 'AA Non Teaching Staff'

    I need a solution or a power shell command or a script that would search the users with a specific TITLE as above and add the users to the relevant groups. and we want to automate this in O365.

    How to do this? Do you think it's possible?

    Thank you.
    Gus

    Reply
    1. Hi,
      If i understand your requirement ,you want to search in AD with specific title 'AA teaching staff' ,if user with this title found ,add to specific group ? If this is true ,how frequent do you run this query ?
      Where do you run this on ? is it On-prem domain or Office 365 Azure AD ?

      Thanks,
      Eswar

      Reply

Leave a Reply to Augustine Gus Cancel reply