Office 365 PowerShell

PowerShell Automation: Save password in a file for further use

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 = “”

$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


  1. There is one big warning !!! :

    Your password can be exposed to everyone !!!



  2. 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


  3. You can also save the entire credential to an xml file:
    $cred = Get-Credential “”
    $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.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: