Passing Connection as Input Parameter in PowerShell Functions

Introduction

Recently, I have come across a scenario where it is required to pass the connection as an input parameter in the PowerShell function. This feature enables only connecting to the admin connection one time during the script execution and using the same connection whenever needed, thus increasing code efficiency. This method can also be used to connect to SPO sites from 3rd party applications.

Here I am declaring a function to get the Site Information in an M365 Tenant that satisfies conditions. Let’s see how we can achieve this using PowerShell functions.

Prerequisites

  • VS code version 1.98+
  • PnP PowerShell module
  • Azure App Registration with API permissions using ‘Graph’ with ‘Sites.FullControl.All’ and have admin consent granted.

Simple Function

The function can be defined as a block of code that does a specific task and may or may not accept arguments. Let’s see how a simple function can be defined.

To define a function, use the `function` keyword followed by the function name.

Function Greet-User {
    Param (
        [string]$Name
    )

    Write-Output "Hello, $Name"
}

Simple function

Output

Steps

Step 1. Define the connection parameters

$SPOAdminUrl = "https://contoso-admin.sharepoint.com"
$TenantID = "abcde-1214-419a-a16b-3580121vvcvd";
$ClientId = "123456789-9655-abcd-9342-1232456578"
$ThumbPrint = "ABCDEFGHIJ121454545554FJFJFJWIWI";
$CurrentDate = Get-Date
$DateFormat = $CurrentDate.ToString('MM-dd-yyyy_hh-mm-ss')

Step 2. Connect to the SPO admin and store the connection in a variable.

$SPOAdminConnection = Connect-PnPOnline -Url $SPOAdminUrl -ClientId $ClientId -Thumbprint $ThumbPrint -Tenant $TenantID -ReturnConnection

Step 3. Pass the connection as a parameter as an input function. Here, we are defining input parameter $AdminConnection as mandatory and its of type ‘object’.

Syntax

function FunctionName {

    [OutputType([string[]])]

    param (

        [Parameter(Mandatory = $true)]
        [object]$AdminConnection

    )

Actual Code

function Get-QASites {

    [OutputType([string[]])]

    param (

        [Parameter(Mandatory = $true)]

        [object]$AdminConnection

    )

    $SitesInfo = @()

    Write-Host "Working on generating the QA sites information..." -ForegroundColor Yellow

    #Get all the site collections

    $LatestSites = Get-PnPTenantSite -Connection $AdminConnection

    #Filter the sites that has title starting with GPPM

    $FilteredSites = $LatestSites | Where-Object { $_.Title -like "QA*" } | Select-Object Title, Url

    foreach ($site in $FilteredSites) {

        $SitesInfo += New-Object PSObject -Property @{

            'SiteTitle'  = $site.Title

            'SiteUrl' = $site.Url        

        }

    }

    Write-Host "Completed generating the QA sites information!!!" -ForegroundColor Green

    return $SitesInfo      

}

Step 4. Validate the output file that is generated from the script.

Complete Script

<#
.SYNOPSIS
Retrieves QA (Quality Assurance) site connection parameters.

.DESCRIPTION
The Get-QASites script is designed to fetch and display 
connection parameters for QA sites. This can be useful for administrators 
managing Group Policy Preferences and needing to understand or troubleshoot 
site-specific configurations.

#>
function Get-QASites {
    [OutputType([string[]])]
    param (
        [Parameter(Mandatory = $true)]
        [object]$AdminConnection
    )
    $SitesInfo = @()
    Write-Host "Working on generating the QA sites information..." -ForegroundColor Yellow
    #Get all the site collections
    $LatestSites = Get-PnPTenantSite -Connection $AdminConnection
    #Filter the sites that has title starting with QA
    $FilteredSites = $LatestSites | Where-Object { $_.Title -like "QA*" } | Select-Object Title, Url
    foreach ($site in $FilteredSites) {
        $SitesInfo += New-Object PSObject -Property @{
            'SiteTitle'  = $site.Title
            'SiteUrl' = $site.Url        
        }
    }
    Write-Host "Completed generating the QA sites information!!!" -ForegroundColor Green
    return $SitesInfo       
}
#Replace with your org SharePoint admin Url
$SPOAdminUrl = "https://contoso-admin.sharepoint.com"
#Replace with your org tenant ID
$TenantID = "abcde-1214-419a-a16b-3580121vvcvd";
#Replace with your app id set up for connecting to all SPO sites in your tenant
$ClientId = "123456789-9655-abcd-9342-1232456578"
#Replace with your thumprint that got generated with thumbprint that got generated with public key is uploaded in App registration
$ThumbPrint = "ABCDEFGHIJ121454545554FJFJFJWIWI";
$CurrentDate = Get-Date
$DateFormat = $CurrentDate.ToString('MM-dd-yyyy_hh-mm-ss')
$SitesInfoCSVPath = "C:\Temp\" + "SiteInformationReport" + $DateFormat + ".csv"
$SPOAdminConnection = Connect-PnPOnline -Url $SPOAdminUrl -ClientId $ClientId -Thumbprint $ThumbPrint -Tenant $TenantID -ReturnConnection
$QASites = Get-QASites -AdminConnection $SPOAdminConnection
$QASites | Export-Csv -Path $SitesInfoCSVPath
Write-Host "The site report is available at location $($SitesInfoCSVPath)" -ForegroundColor Green

References: https://pnp.github.io/powershell/

Up Next
    Ebook Download
    View all
    Learn
    View all