private/Update-Pstn.ps1

function Update-Pstn {
    Param ([PSObject]$teamToCheck, [Boolean]$waitForLicense)
    if ( $teamToCheck.teamServiceDetails.PsObject.Properties.name -eq 'pstnEnabled' -and -not $teamToCheck.teamServiceDetails.pstnEnabled ) {
        Remove-PhoneLicense($teamToCheck.applicationId)
        return $true
    }
    if ($teamToCheck.teamServiceDetails.pstnEnabled) {
        $hasPstn = New-PhoneLicense -ObjectId $teamToCheck.applicationId -WaitForLicense $waitForLicense
        if ( -not $hasPstn ) {
            $teamToCheck.teamServiceDetails.PsObject.Properties.Remove('pstnEnabled')
            $teamToCheck.teamServiceDetails.PsObject.Properties.Remove('pstnNumber')
            return $true
        }
        if ( $hasPstn -and -not [string]::IsNullOrEmpty($teamToCheck.teamServiceDetails.pstnNumber) ) {
            $hasPstn = Update-PhoneNumber -ObjectId $teamToCheck.applicationId -PstnNumber $teamToCheck.teamServiceDetails.pstnNumber
            # We assigned the licenses if this does not work we will try again in the end
            if ( -not $hasPstn ) {
                $pstnExistsAlready = Find-CsOnlineApplicationInstance -SearchQuery $teamToCheck.teamServiceDetails.pstnNumber -ExactMatchOnly
                if ( $pstnExistsAlready ) {
                    Write-Output " PSTN Number is already occupied by another Application Instance. Please use an unoccupied one."
                    $teamToCheck.teamServiceDetails.PsObject.Properties.Remove('pstnNumber')
                    return $true
                }
                # Check if another ApplicationInstance has the pstnNumber set already
                return $false
            }
        }
    }
    elseif ( -not [string]::IsNullOrEmpty($teamToCheck.teamServiceDetails.pstnNumber) ) {
        $hasPstn = Update-PhoneNumber -ObjectId $teamToCheck.applicationId -PstnNumber $teamToCheck.teamServiceDetails.pstnNumber
        if ( -not $hasPstn ) {
            $teamToCheck.teamServiceDetails.PsObject.Properties.Remove('pstnEnabled')
            $teamToCheck.teamServiceDetails.PsObject.Properties.Remove('pstnNumber')
        }
    }
    return $true
}