We help IT Professionals succeed at work.

Powershell: Using credentials stored in Credential Manager

I'm creating a script to connect to Office 365, Exchange/SharePoint/Skype for Business Online, etc to automate a couple of tasks. Usually when I start the script, I'm required to enter my office 365 credentials to complete the connection process. Is it possible to store the credentials within the "Credential Manager", then have the PS script obtain the credentials from there? Any suggestions? Thank you for your time.
Comment
Watch Question

CERTIFIED EXPERT
Most Valuable Expert 2015
Distinguished Expert 2019
Commented:
Yes, it's possible and there is a sample script available here: https://gallery.technet.microsoft.com/scriptcenter/PowerShell-Credentials-d44c3cde
Senior Network Consultant / Engineer
CERTIFIED EXPERT
Commented:
You can store your password in a secure string if you like.

To save your password:
$O365PWFile = "C:\o365pw"
(ConvertFrom-SecureString (Read-Host "Enter your password" -AsSecureString)).ToString() | Add-Content $O365PWFile

Open in new window

This stores the password in a text file that can only be decrypted by the user that created it.
Then to use it:
$O365PWFile = "C:\o365pw"
$o365UN = "admin@domain.onmicrosoft.com"
$secstring = (Get-Content $O365PWFile).Trim() | ConvertTo-SecureString
$O365creds = New-Object System.Management.Automation.PSCredential -ArgumentList $o365UN,$secstring

$Session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri https://ps.outlook.com/powershell/ -Credential $O365creds -Authentication Basic -AllowRedirection
Import-PSSession $Session
Connect-MsolService -Credential $O365creds

Open in new window

Change the variables to suit your environment.
Domenic DiPasqualeSystems Administrator II

Author

Commented:
Thank you for the suggestions. I'll test the recommendations and follow up later this week.
Domenic DiPasqualeSystems Administrator II

Author

Commented:
I apologize for the delay in response. I was able to setup my script(s) to use credentials store in a file. Thank you for your help.
Jeremy WeisingerSenior Network Consultant / Engineer
CERTIFIED EXPERT

Commented:
Glad to help. :)