How to Use a Encrypted Password File in PowerShell Scripts?

Requirement: Use a encrypted password file in PowerShell scripts.
How to Use a Encrypted Password File in PowerShell Scripts?

How to use a Encrypted Password File to Read/Write Credentials in PowerShell?
PowerShell modules like PnP PowerShell offers a mechanism to use Windows credentials store to Save and retrieve user name and password to use it in scripts. However, for other PowerShell modules like SharePoint Online Management Shell, AzureAD, CSOM. etc. we don't have any direct ways to suppress the password prompt, other than storing the password in plain text within the script. In situations like we need to schedule the script in Windows task scheduler, for unattended execution of the script without any user intervention, we can use this method:

Here is how we can store and read encrypted passwords from file in PowerShell scripts.
MFA must be turn-off for the saved credentials to work!
  • Step 1: Create a encrypted password file to store credentials
  • Step 2: Read the encrypted password from the file and use it in scripts.

Create a Encrypted Password File
Basically, we need to get the credentials from the user (once!) and store the encrypted password to a file. Here is the PowerShell script to save encrypted password to a file.
#function to Save Credentials to a file
Function Save-Credential([string]$UserName, [string]$KeyPath)
{
    #Create directory for Key file
    If (!(Test-Path $KeyPath)) {        
        Try {
            New-Item -ItemType Directory -Path $KeyPath -ErrorAction STOP | Out-Null
        }
        Catch {
            Throw $_.Exception.Message
        }
    }
    #store password encrypted in file
    $Credential = Get-Credential -Message "Enter the Credentials:" -UserName $UserName
    $Credential.Password | ConvertFrom-SecureString | Out-File "$($KeyPath)\$($Credential.Username).cred" -Force
}

#Get credentials and create a encrypted password file
Save-Credential -UserName "[email protected]" -KeyPath "C:\Scripts"
This creates a file with encrypted credentials on given path.

Get the encrypted password from the File
Once we create the encrypted password file, we can read the file and use the saved credentials in our scripts like:
#function to get credentials from a Saved file
Function Get-SavedCredential([string]$UserName,[string]$KeyPath)
{
    If(Test-Path "$($KeyPath)\$($Username).cred") {
        $SecureString = Get-Content "$($KeyPath)\$($Username).cred" | ConvertTo-SecureString
        $Credential = New-Object System.Management.Automation.PSCredential -ArgumentList $Username, $SecureString
    }
    Else {
        Throw "Unable to locate a credential for $($Username)"
    }
    Return $Credential
}

#Get encrypted password from file
$Cred = Get-SavedCredential -UserName "[email protected]" -KeyPath "C:\Scripts"

#Connect to Azure AD from saved credentials
Connect-AzureAD -Credential $Cred    

Alright, here is how we can use this method to connect to SharePoint Online Management Shell:
#Get encrypted password from file
$Cred = Get-SavedCredential -UserName "[email protected]" -KeyPath "C:\Scripts"

#Connect to SharePoint Online PowerShell
Connect-SPOService -URL "https://crescentintranet-admin.sharepoint.com" -Credential $Cred

#Get all Site Collections
Get-SPOSite
    
Similarly, to connect to SharePoint Online using CSOM PowerShell, use:
Import-Module Microsoft.Online.SharePoint.PowerShell

#Get encrypted password from file
$Cred = Get-SavedCredential -UserName "[email protected]" -KeyPath "C:\Scripts"

#Parameter
$SiteUrl = "https://crescentintranet.sharepoint.com/sites/marketing"
    
#Set up the context
$Ctx = New-Object Microsoft.SharePoint.Client.ClientContext($SiteUrl)
$Ctx.Credentials = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($Cred.Username, $Cred.Password)
 
#Get the Web Object
$Web = $Ctx.web
$Ctx.Load($Web)
$Ctx.ExecuteQuery()
 
#Get the Title of the Web
Write-host $Web.Title  
I used it in automated PowerShell scripts that's scheduled in Windows task scheduler. E.g. PowerShell to import custom user profile properties from Azure AD to SharePoint Online user profile store.

No comments:

Please Login and comment to get your questions answered!

Powered by Blogger.