Login to Azure/Office 365 in a script

How you can programmatically login to Azure/Office 365 in a script.

1
2
3
4
5
6
$username = "user@domain.com"
$pwdFilePath = "C:\Temp\MyPassword.txt"
Read-host -assecurestring | convertfrom-securestring | out-file $pwdFilePath # COMMENT OUT IN SCRIPT
$pwdTxt = Get-Content $pwdFilePath
$securePwd = $pwdTxt | ConvertTo-SecureString # DO NOT CHANGE THIS LINE
$credObject = New-Object System.Management.Automation.PSCredential -ArgumentList $username, $securePwd