public/New-SfWebSession.ps1

function New-SfWebSession {

    [CmdletBinding()]
    param (
        [Parameter(Mandatory, Position = 0)]
        [string] $TargetOrg
    )

    $ErrorActionPreference = 'Stop'
    [bool] $IsDebug   = $DebugPreference   -ne 'SilentlyContinue'
    [bool] $IsVerbose = $VerbosePreference -ne 'SilentlyContinue'

    # --- extract the access token via SF CLI
    $SfAccessToken = sf org auth show-access-token --no-prompt --json --target-org $TargetOrg | ConvertFrom-Json
    if ($SfAccessToken.status -ne 0) {
        Write-Error "Cannot get access token (sf org auth show-access-token) for $TargetOrg"
        return
    }

    # --- get the OrgInfo via SF CLI
    $SfOrgInfo = sf org display --json --target-org $TargetOrg | ConvertFrom-Json
    if ($SfOrgInfo.status -ne 0) {
        Write-Error "Cannot get org info (sf org display) for $TargetOrg"
        return
    }
    Write-Verbose "New-SfWebSession|instanceUrl=$($SfOrgInfo.result.instanceUrl)"
    Write-Verbose "New-SfWebSession|username=$($SfOrgInfo.result.username)"

    # --- initial dummy http GET to initiate a web request session
    [uri]$SfInstance = $SfOrgInfo.result.instanceUrl
    $url = $SfInstance.AbsoluteUri
    $null = Invoke-WebRequest -Method Get -SessionVariable WebSession -Uri $url

    # --- inject a cookie with our access token
    $cookie = New-Object System.Net.Cookie
    $cookie.Name = "sid"
    $cookie.Value = $SfAccessToken.result.accessToken
    $cookie.Domain = $SfInstance.Authority # only the fqdn without https://
    $WebSession.Cookies.Add($cookie)

    # --- put together our return object
    return [PSCustomObject]@{
        PSTypeName  = 'SfMetadataToolkit.WebSession'
        WebSession  = $WebSession
        InstanceUrl = $SfOrgInfo.result.instanceUrl
    }
}