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

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.

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