How to Pass Credentials as Parameters in PowerShell

Introduction

There could be a scenario where it is required to pass the credentials securely from one method to another with in a program. Here I have chosen my scripting language as PowerShell and used PowerShell ISE for demo with version 5.1. Let me put up a small script that reads the credentials from user and passes it to a method. Below is the pseudo-code.

Function FunctionName {
    param(
        $Param1,
        $Param2
    )

    # Logic to perform the task
}

# Script to read the user input

Below is the PS script to read the credentials. i have used parameter type PSCredential which is coming from namespace System.Management.Automation.

#Demo for Passing credentials as parameters
function ReadCredentials {
    param(
      [PSCredential]$Credentials
    )
    Write-Host "User name: $($Credentials.UserName)`nPassword: $($Credentials.Password)" -ForegroundColor Yellow

}
$SiteCredentials=Get-Credential
ReadCredentials -Credentials $SiteCredentials

Below is the screen capture of the output.

Output image

In the bigger picture, the same logic is being implemented in one of my business use cases, where I got to update a site title for the existing site in SharePoint online.

The use case here is to update a Site Title using the SPO PowerShell module. I have modified the script to run as a function and called the functions with credentials passed as parameters.

Pre-requisites

  • The service account/user account used to run the script should have SharePoint admin rights enabled.
  • Access to PowerShell 5 or VS code or any IDE that supports PowerShell CSOM
  • We need to have the following PS modules installed
    • Microsoft.Online.SharePoint.PowerShell
    • PSLogging

Note: Kindly refer to the references section on how to install these required modules.

Steps

Step 1. Define the function to get the SharePoint online site using the SPO PowerShell module.

Here, I define the following parameters:

  • ‘$SiteUrl’ of type ‘string’.
  • ‘$LogFile’ of type ‘string’
  • ‘UpdatedTitle’ of type ‘string’
  • ‘$SiteCredentials’ of type ‘PSCredential’
Function UpdateSiteTitle{
    param
    (
        [string]$SiteUrl,
        [string]$LogFile,
        [string]$UpdatedTitle,
        [System.Management.Automation.PSCredential]$AdminCredentials
        
    )
    try {     
  
        #Setup the context
        $Ctx = New-Object Microsoft.SharePoint.Client.ClientContext($SiteUrl)
        $SiteCredentials = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($AdminCredentials.UserName,$AdminCredentials.Password)
        $Ctx.Credentials = $SiteCredentials
 
        #Get the Site from URL
        $Web = $Ctx.web
        $Ctx.Load($web)
        $Ctx.ExecuteQuery()
  
        #Get the current site title
        Write-host "Site Title:"$web.title
 
        #sharepoint online powershell change site title
        $web.title = $UpdatedTitle    
        Write-LogInfo -Message "Updating Site Title for the site $($SiteUrl)" -LogPath $LogFile -TimeStamp
        $Web.Update()
        $Ctx.ExecuteQuery()
      
        Write-host "Site Title has been updated!" -ForegroundColor Green 
        Write-LogInfo -Message "Updated site title for the site $($SiteUrl)" -LogPath $LogFile -TimeStamp

    }
    catch {
        Write-Host "Error occured while updating the title for url $($SiteUrl)" -ForegroundColor Red
        $ExceptionError = $_.Exception.Message
        Write-Host $_.Exception.Message -ForegroundColor Red
        Write-LogError -Message "Error occured while updating the title for url $($SiteUrl)\n$($ExceptionError)" -LogPath $LogFile -TimeStamp
    }
}
#Module to record the operations during the script execution
Import-Module -Name PSLogging
#Please update your service account that has SharePoint admin rights
$AdminAccount="[email protected]"
$SPOAdminUrl = "https://contoso-admin.sharepoint.com"
$Creds = Get-Credential -UserName $AdminAccount -Message "Connecting to SPO Service"
Connect-SPOService -Url $SPOAdminUrl -Credential $Creds
$SiteURL="https://contoso.sharepoint.com/teams/M365POC4"
Set-SPOUser -Site $SiteURL -LoginName $AdminAccount -IsSiteCollectionAdmin $true
UpdateSiteTitle -SiteUrl $SiteURL -LogFile "C:\SPOMigration\Output\Logs03082024.txt" -UpdatedTitle "Microsoft365 Proof Of Concept" -AdminCredentials $Creds

Validation

pass credentials as parameters using PS objects

It is getting the current site title, and the update is successful.

pass credentials as parameters using PS objects

Conclusion

Thus, in this article, we have seen how to pass credentials as parameters using PS objects.

References