When you want to use PowerShell with a service, in most cases you will need to authenticate to that service. If you are looking to automate, trivial task, you will need some kind of mechanism to load your credentials from a separate, secure location so you don’t need to be available when the script runs. Of course you can save the password in the file but that isn’t really secure.
Part 1: Retrieve password from the user and save it into a file
$username = “admin@testaadjsol.onmicrosoft.com”
$secureString = read-host “Please provide password for Office 365” | ConvertTo-SecureString -AsPlainText -Force
$secureStringText = $secureString | ConvertFrom-SecureString
Set-Content “c:\scripts\passwordtest.txt” $secureStringText
Part 2: Load from a file and connect to the service. In this case the service is Office 365.
$secureString = Get-Content “C:\scripts\passwordtest.txt” | ConvertTo-SecureString
$myCredentials = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $username, $secureString
Connect-MsolService -Credential $myCredentials
There is one big warning !!! :
Your password can be exposed to everyone !!!
$myCredentials.GetNetworkCredential().Domain
$myCredentials.GetNetworkCredential().UserName
$myCredentials.GetNetworkCredential().Password
LikeLike
I would assume if this is a shared computer, this would a service account people use. It is not a best practice to use your personal account in this. But good to point it out.
LikeLike
I store my cred info to my desktop, only I can access it… if shared computer why not use a scheduled task where you can set the account the task will run with
LikeLike
You can also save the entire credential to an xml file:
$cred = Get-Credential “admin@testaadjsol.onmicrosoft.com”
$cred | Export-clixml c:\scripts\admin.xml
Then recreate and import
$cred = Import-Credential c:\scripts\admin.xml
And yes, you still need to protect that file and access to your computer.
LikeLike