Automate connecting to Office 365 with PowerShell

[vc_row][vc_column][vc_column_text]Connecting to Office 365 with PowerShell enables you to perform many functions not available in the GUI.  But what if you want to automate these functions.  Connecting to Office 365 with PowerShell will prompt you for credentials for that session.  Now credentials can be saved in the script but that would be a security issue having your password saved in a file.  The way around that would be to save your password as a secure string in a text file.  And that is easy:

Read-Host -Prompt “Enter your password” -AsSecureString | ConvertFrom-SecureString | Out-File “C:\scripts\cred.txt

Your password will be encrypted and look like this:

$AdminName = “admin@domain.onmicrosoft.com”
$Pass = Get-Content “c:\scripts\cred.txt” | ConvertTo-SecureString
$Cred = new-object -typename System.Management.Automation.PSCredential -argumentlist $AdminName, $Pass
$Session = New-PSSession`
-ConfigurationName Microsoft.Exchange -ConnectionUri https://outlook.office365.com/powershell-liveid/`
-Credential $cred -Authentication Basic -AllowRedirection

Import-PSSession $Session

After the connection part you can add your desired function to the script.  Let’s say for instance you want to export a list of shared mailboxes.

Get-Mailbox -RecipientTypeDetails SharedMailbox -ResultSize Unlimited | Select DisplayName | sort DisplayName | Export-Csv c:\scripts\SharedMailboxes.csv -NoTypeInformation

**This illustrates how an O365 administrator can introduce automation in scripts that they own and control individually. For scheduling automation tasks it is recommended to use a dedicated service account.[/vc_column_text][/vc_column][/vc_row]

Share:

Facebook
Twitter
LinkedIn

Contact Us

Name
=
On Key

More Posts

Microsoft Intune Suite: Enterprise Application Management
Endpoint Management

Microsoft Intune Suite: Enterprise Application Management

Maintaining applications across an organization has always been one of the most time‑consuming tasks for your endpoint management team. Packaging installers, writing detection rules, testing deployments, and troubleshooting failures can eat up hours and days of

Read More »
Migrating to M365 Part 5: Microsoft Purview
Tech Mergers & Acquisitions

Migrating to M365 Part 5: Microsoft Purview

This guide is part of our M365 Migration Series. Explore every step of the tenant-to-tenant migration journey below: Part 1 Part 2 Part 3 Part 4 Part 5 Mergers and acquisitions often bring the challenge of

Read More »
Migrating to M365 Part 4: Microsoft Defender
Tech Mergers & Acquisitions

Migrating to M365 Part 4: Microsoft Defender

This guide is part of our M365 Migration Series. Explore every step of the tenant-to-tenant migration journey below: Part 1 Part 2 Part 3 Part 4 Part 5 Mergers and acquisitions often bring the challenge of

Read More »