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 within 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 the 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 comes from the 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
}
# Prompt user for credentials
$SiteCredentials = Get-Credential
# Pass credentials to the function
ReadCredentials -Credentials $SiteCredentials

Below is the screen capture of the output.

Output

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)"
    
            # Update SharePoint Online 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 occurred while updating the title for URL $($SiteUrl)" -ForegroundColor Red
            $ExceptionError = $_.Exception.Message
            Write-Host $_.Exception.Message -ForegroundColor Red
            Write-LogError -Message "Error occurred while updating the title for URL $($SiteUrl)`n$($ExceptionError)" -LogPath $LogFile -TimeStamp
        }
    }
    
    # Module to record operations during script execution
    Import-Module -Name PSLogging
    
    # Please update your service account with 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

Validation

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

Microsoft

Conclusion

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

References

Up Next
    Ebook Download
    View all
    Learn
    View all