CxdCallData.psm1


function Get-CxdCallData{

    <#
 
        .SYNOPSIS
 
        Retrieves a series of data using Get-CsUserSession including:
 
        -Rate my Call data (all data is available including surveys closed without a response)
        -MediaLines data relevant to determine what endpoints are being used in a call
        -LastLogonDate which tells us if people have signed in and when
        -Client versions (normalized)
        -Other useful data for understanding usage in the tenant
 
 
        .DESCRIPTION
 
        First, the Get-CxdCallData script will ask the user for credentials to authenticate to Skype for Business Online. If previous credentials are found we will ask to reuse them otherwise we'll ask for new ones.
 
        Second, the script will ask if there is a CSV file for input. This file must have a header column of 'UserPrincipalName' as this is what we use to find enabled users in the tenant. You can use the format of 'lastname, firstname' or 'firstname lastname' or 'firstname.lastname@domain.com'. The script will handle searching for users matching the criteria and formatting them into a common UPN format to perform the search.
 
        Lastly, the script will output (by default) the results to an HTML file in the path you ran it from. The file name will include the current date and time incorporated into the file.
 
        For the CSV file, the following formats are supported:
 
        Firstname,Lastname,Userprincipalname
        Jason,Shave,jassha@microsoft.com
 
        or
 
        Userprincipalname
        jassha@microsoft.com
 
        or
 
        Userprincipalname
        Shave, Jason
 
 
        .EXAMPLE
 
        Get-CxdCallData -NumberOfDaysToSearch 90 -CsvFileWithUsers C:\users\jason\documents\customerdata\users.csv -ReportSavePath C:\users\jason\documents\customerdata
 
        .EXAMPLE
 
        Get-CxdCallData -NumberOfDaysToSearch 180 -ReportSavePath C:\users\jason\documents -Verbose
 
        .NOTES
 
        You must be a Skype for Business Administrator in the Office 365 tenant to run the commands in this script. This script is provided without warranty. Although the commands and functions within this script do not make changes to your Office 365 tenant, you agree to use it at your own risk.
 
        Created by: Jason Shave (jassha@microsoft.com)
    #>


    [cmdletbinding()]
        Param
        (
        [Parameter(Mandatory=$true)]
        [int]$NumberOfDaysToSearch,

        [Parameter(Mandatory=$false)]
        [string]$CsvFileWithUsers,

        [Parameter(Mandatory=$true)]
        [string]$ReportSavePath,

        [Parameter(Mandatory=$false)]
        [string]$OverrideAdminDomain
        )

    begin {
        #note the .AddDays is subtracting the number of days to search
        $startTime = (Get-Date).AddDays(-$NumberOfDaysToSearch)
        $endTime = Get-Date
        $global:sessionStartTime = $null
        $numBuckets = 0
        $numUsers = 0
        $enabledUsers = $null
        $arrNotUsingSkype = $null
        $global:credential = Get-Credential -Message "Authenticate to Skype for Business Online"
    }

    process {
        Invoke-CxdSkypeOnlineConnection
        Set-CxdSavePath -ReportSavePath $ReportSavePath

        try{
            [array]$enabledUsers = Get-CxdSkypeOnlineUsers -CsvFileWithUsers $CsvFileWithUsers
        }catch{
            Write-Warning -Message "Cannot connect to Skype Online due to a broken or stale connection. Attempting to remove and retry."
            Invoke-CxdSkypeOnlineConnection -RepairPSSession
            [array]$enabledUsers = Get-CxdSkypeOnlineUsers -CsvFileWithUsers $CsvFileWithUsers
        }
        
        if (!$enabledUsers.Count){
                Write-Warning -Message "We didn't find any users matching your query. Exiting..."
                break;
        }else{
            Write-Verbose -Message "Putting $($enabledUsers.Count) users into buckets..."
            $userTotal = $enabledUsers.Count
            $userBuckets = [math]::Ceiling($userTotal /10)
            $arrUserBuckets = @{}
            $count = 0
            $enabledUsers | ForEach-Object {
                $arrUserBuckets[$count % $userBuckets] += @($_)
                $count++
            }
        }
        Write-Verbose -Message "Placed $($enabledUsers.Count) users into $($arrUserBuckets.Count) bucket(s)."
        $pStart = Get-Date
        foreach ($userItem in $arrUserBuckets.Values){

            #progress bar for total buckets
            $numBuckets++
            $bId = 1
            $bActivity = "Processing " + $enabledUsers.Count + " users into " + $arrUserBuckets.Count + " buckets."
            $bStatus = "Bucket #" + $numBuckets
            [int]$bPercentComplete = ($numBuckets/($arrUserBuckets.Count + 1)) * 100
            $bCurrentOperation = [string]$bPercentComplete + "% Complete"
            if ($bSecondsRemaining){
                Write-Progress -Activity $bActivity -Status $bStatus -Id $bId -PercentComplete $bPercentComplete -CurrentOperation $bCurrentOperation -SecondsRemaining $bSecondsRemaining
            }else{
                Write-Progress -Activity $bActivity -Status $bStatus -Id $bId -PercentComplete $bPercentComplete -CurrentOperation $bCurrentOperation
            }
            #reset numUsers to prevent over 100% being interpreted
            $numUsers = 0
            foreach($userI in $userItem){
                $numUsers ++
                $uId = 2
                $objLastLogon = $null
                $audioSessions = $null
                $objLastLogon = $null

                $uActivity = "Processing users..."
                $uStatus = "Gathering user session report for " + $userI.UserPrincipalName
                [int]$uPercentComplete = ($numUsers/($userItem.Count +1)) * 100
                $uCurrentOperation = [string]$uPercentComplete + "% Complete"

                Write-Verbose -Message "Getting user session data for $($userI.UserPrincipalName)"
                Write-Progress -Activity $uActivity -Status $uStatus -Id $uId -PercentComplete $uPercentComplete -CurrentOperation $uCurrentOperation -ParentId $bId

                try{
                    #clear error for getting user session data since this times out after a few hours and we need to re-auth
                    $getUserSessionError = $null
                    Invoke-CxdSkypeOnlineConnection
                    [array]$userSession = Get-CsUserSession -StartTime $startTime -EndTime $endTime -User $userI.UserPrincipalName -WarningAction SilentlyContinue -ErrorVariable $getUserSessionError
                }catch{
                    #$getUserSessionError = $_.Exception.Message
                    Write-Error -Message "Unable to retrieve user session information. Attempting to repair the Skype Online connection and will try again."
                    Invoke-CxdSkypeOnlineConnection -RepairPSSession
                    [array]$userSession = Get-CsUserSession -StartTime $startTime -EndTime $endTime -User $userI.UserPrincipalName -WarningAction SilentlyContinue -ErrorVariable $getUserSessionError
                }finally{
                    if ($getUserSessionError){
                        $getUserSessionError
                        #throw;
                    }
                }
                #we need this if block since the Get-CsUserSession could complete correctly but throw an error not caught by the try/catch block


                if ($userSession.count -eq 0){
                    #build array for report of people not using skype
                    [array]$arrNotUsingSkype += [PSCustomObject]@{
                        UsersNotUsingSkype = $userI.UserPrincipalName
                    }
                }else{
                    [array]$objLastLogon = $usersession | Where-Object MediaTypesDescription -eq "[RegisterEvent]" | Sort-Object EndTime -Descending
                    if ($objLastLogon) {
                        $objLastLogon = $objLastLogon[0] #get most recent logon
                    }else{
                        #if we have session data for this user but no registration in the past 'x' days, they must be an on-premises user.
                        $objLastLogon = "On-premises user"
                    }

                    #get client versions for all Register events then scrub them for blanks and build an array of all users
                    $clientVersions = $userSession | Where-Object MediaTypesDescription -eq "[RegisterEvent]" | Sort-Object EndTime -Descending | Select-Object @{Name="UserPrincipalName";Expression={$_.FromUri}},@{Name="Version";Expression={$_.FromClientVersion}},@{Name="Date";Expression={$_.StartTime}} | Where-Object Version -ne ""
                    [array]$arrClientVersionsScrubbed += $clientVersions | Select-Object @{Name="User";Expression={$userI.UserPrincipalName}},@{Name="Version";Expression={$_.Version}} -Unique
                    [array]$audioSessions = $userSession | Where-Object MediaTypesDescription -like "*Audio*"
                    
                    #build array for report (if we have an audiosession)
                    if ($audioSessions){
                        #build report for user feedback
                        [array]$arrUserFeedback += $audioSessions | Where-Object {$_.QoeReport.FeedbackReports} | ProcessFeedback
                        #build report for user summary
                        [array]$arrUserSummary += ProcessUserSummary -userSummaryInput $audioSessions -UserPrincipalName $userI.UserPrincipalName
                        #build report for failed calls
                        [array]$arrFailedCalls += $audioSessions | Where-Object {$_.ErrorReports.ErrorCategory -eq "UnexpectedFailure"} | ProcessFailedCalls
                    }
                }
            }
            $pElapsed = (Get-Date) - $pStart
            $bSecondsRemaining = ($pElapsed.TotalSeconds / $numBuckets) * (($arrUserBuckets.Count + 1) - $numBuckets)
            Write-Progress -Activity $bActivity -Status $bStatus -Id $bId -PercentComplete $bPercentComplete -SecondsRemaining $bSecondsRemaining -CurrentOperation $bCurrentOperation
        }

        #process report data
        ProcessReports
    }
    
    end{
        Write-Verbose -Message "Removing PowerShell Session..."
        Get-PSSession | Remove-PSSession
    }   
}

function ProcessFeedback{
    begin{}
    process{
        #$feedbackInput | ForEach-Object {
            if ($_.QoeReport.FeedbackReports -eq $null){
                continue; #no feedback report found
            }
            #check for multiple QoE reports in this call (very rare)
            if ($_.QoeReport.FeedbackReports.Count -gt 1){
                $_.QoeReport.FeedbackReports = $_.QoeReport.FeedbackReports | Where-Object FromUserUri -eq $userI.UserPrincipalName
            }
            #process feedback tokens from array into string to present back as an object we can report on
            if ($_.QoeReport.FeedbackReports.tokens | Where-Object Value -ne "0"){
                [array]$arrTokens = $_.QoeReport.FeedbackReports.tokens | Where-Object Value -ne "0" | Select-Object Id #declare an array so we can get the count. if the count is only one, the trim statement preceding won't make sense so we need to handle this.
                if ($arrTokens.Count -gt "1"){
                    $arrTokens = $arrTokens.id.trim() -join "," #output would show System.Object[] in the report otherwise so we need to convert them to a string.
                }
            }else{
                $arrTokens = ""
            }
            #process traceroute collection for each call and pull back interesting information.
            $strTraceRoutes = ProcessTraceRoutes -Call $_

            #build array of objects with interesting information about the poor feedback for this given call.
            try{
                $newObject = [PSCustomObject][ordered]@{
                    FromUri = $_.FromUri
                    ToUri = $_.ToUri
                    CaptureTime = $_.QoeReport.FeedbackReports.CaptureTime
                    Rating = $_.QoeReport.FeedBackReports.Rating
                    FeedbackText = $_.QoeReport.FeedBackReports.FeedbackText
                    Tokens = $arrTokens.Id
                    MediaType = $_.MediaTypesDescription
                    ConferenceUrl = $(if ($_.ConferenceUrl){$_.ConferenceUrl}else{"N/A"})
                    FromClientVersion = $_.FromClientVersion
                    ToClientVersion = $_.ToClientVersion
                    MediaStartTime = $_.QoeReport.Session.MediaStartTime
                    MediaEndTime = $_.QoeReport.Session.MediaEndTime
                    MediaDurationInSeconds = ($_.QoeReport.Session.MediaEndTime - $_.QoeReport.Session.MediaStartTime).Seconds
                    FromOS = $_.QoeReport.Session.FromOS
                    ToOS = $_.QoeReport.Session.ToOS
                    FromVirtualizationFlag = $_.QoeReport.Session.FromVirtualizationFlag
                    ToVirtualizationFlag = $_.QoeReport.Session.ToVirtualizationFlag
                    FromConnectivityIce = $_.QoeReport.MediaLines.FromConnectivityIce
                    FromRenderDev = $_.QoeReport.medialines.FromRenderDev
                    ToRenderDev = $_.QoeReport.MediaLines.ToRenderDev
                    FromNetworkConnectionDetail = $_.QoeReport.MediaLines.FromNetworkConnectionDetail
                    ToNetworkConnectionDetail = $_.QoeReport.MediaLines.ToNetworkConnectionDetail
                    FromIPAddr = $_.QoeReport.MediaLines.FromIPAddr
                    ToIPAddr = $_.QoeReport.MediaLines.ToIPAddr
                    FromReflexiveLocalIPAddr = $_.QoeReport.MediaLines.FromReflexiveLocalIPAddr
                    FromBssid = $_.QoeReport.MediaLines.FromBssid
                    FromVPN = $_.QoeReport.MediaLines.FromVPN
                    ToVPN = $_.QoeReport.MediaLines.ToVPN
                    JitterInterArrival = $(if ($_.QoeReport.AudioStreams){$_.QoeReport.AudioStreams[0].JitterInterArrival}else{"N/A"})
                    JitterInterArrivalMax = $(if ($_.QoeReport.AudioStreams){$_.QoeReport.AudioStreams[0].JitterInterArrivalMax}else{"N/A"})
                    PacketLossRate = $(if ($_.QoeReport.AudioStreams){$_.QoeReport.AudioStreams[0].PacketLossRate}else{"N/A"})
                    PacketLossRateMax = $(if ($_.QoeReport.AudioStreams){$_.QoeReport.AudioStreams[0].PacketLossRateMax}else{"N/A"})
                    BurstDensity = $(if ($_.QoeReport.AudioStreams){$_.QoeReport.AudioStreams[0].BurstDensity}else{"N/A"})
                    BurstDuration = $(if ($_.QoeReport.AudioStreams){$_.QoeReport.AudioStreams[0].BurstDuration}else{"N/A"})
                    BurstGapDensity = $(if ($_.QoeReport.AudioStreams){$_.QoeReport.AudioStreams[0].BurstGapDensity}else{"N/A"})
                    BurstGapDuration = $(if ($_.QoeReport.AudioStreams){$_.QoeReport.AudioStreams[0].BurstGapDuration}else{"N/A"})
                    PayloadDescription = $(if ($_.QoeReport.AudioStreams){$_.QoeReport.AudioStreams[0].PayloadDescription}else{"N/A"})
                    AudioFECUsed = $(if ($_.QoeReport.AudioStreams){$_.QoeReport.AudioStreams[0].AudioFECUsed}else{"N/A"})
                    SendListenMOS = $(if ($_.QoeReport.AudioStreams){$_.QoeReport.AudioStreams[0].SendListenMOS}else{"N/A"})
                    OverallAvgNetworkMOS = $(if ($_.QoeReport.AudioStreams){$_.QoeReport.AudioStreams[0].OverallAvgNetworkMOS}else{"N/A"})
                    NetworkJitterMax = $(if ($_.QoeReport.AudioStreams){$_.QoeReport.AudioStreams[0].NetworkJitterMax}else{"N/A"})
                    NetworkJitterAvg = $(if ($_.QoeReport.AudioStreams){$_.QoeReport.AudioStreams[0].NetworkJitterAvg}else{"N/A"})
                    StreamDirection = $(if ($_.QoeReport.AudioStreams){$_.QoeReport.AudioStreams[0].StreamDirection}else{"N/A"})
                    TraceRoutes = $strTraceRoutes
                    DialogId = $_.DialogId
                }
            }catch{
                Write-Warning -Message "Could not process all Rate My Call feedback data correctly for $($userI.UserPrincipalName)."
            }
        #}
        return $newObject
    }
    end{
    }
}

function ProcessClientVersions{
    [cmdletbinding()]
        Param
        (
        [Parameter(Mandatory=$false)]
        [int]$ClientVersionCutOffDays,

        [Parameter(Mandatory=$true, ValueFromPipeline=$true)]
        [psobject]$ClientVersionData
        )

    begin {}
    process{
        $strClientVersionSplit = $null
        $strClientVersionSplit = [regex]::Match($ClientVersionData, '(\d{4}\.\d{4})').Captures
        if ($strClientVersionSplit.Success -eq $true){
            $strClientVersionSplit = (($strClientVersionSplit.Groups[1]).Value).Split(".") #need this additional line due to null value possibility along with error: "cannot index null array"
            #need to handle scenario where we only have revision and build data
            if ($strClientVersionSplit.count -eq "2"){
                [array]$objClientVersion = [PSCustomObject][ordered]@{
                    Revision = $strClientVersionSplit[0]
                    Build = $strClientVersionSplit[1]
                }
            #handle full version info here...
            }elseif ($strClientVersionSplit.count -eq "4"){
                [array]$objClientVersion = [PSCustomObject][ordered]@{
                    Major = $strClientVersionSplit[0]
                    Minor = $strClientVersionSplit[1]
                    Revision = $strClientVersionSplit[2]
                    Build = $strClientVersionSplit[3]
                }
            }
        }
        return $objClientVersion        
    }
     end{}
}

function ProcessTraceRoutes{
    <#
        .SYNOPSIS
        Internal function used to process traceroute data from QoeReport.
         
        .DESCRIPTION
        We process this array of traceroute data into a string we can export to CSV/HTML.
         
        .PARAMETER TraceRoute
        Object containing the traceroute properties used to build the string we return.
         
        .EXAMPLE
        ProcessTraceRoutes -TraceRoute $objectName
 
    #>


    [cmdletbinding()]
        Param
        (
        [Parameter(mandatory=$true, valuefrompipeline=$false)]
        $Call
        )
        begin{
            if ($Call.QoeReport.TraceRoutes -eq $null){
                $networkPath = $null
            }else{
                $call.qoereport.TraceRoutes | ForEach-Object {
                    $networkPath = $networkPath + "Hop:" + $($_.hop) + ",IP:" + $($_.IPAddress) + ",RTT:"+ $($_.RTT) + ";"
                }
                return $networkPath
            }
        }
        end{}

}

function ProcessReports{
    begin{}
    process{
        if ($arrUserSummary){
            Write-Verbose -Message "Exporting user summary report."
            Export-CxdData -DataInput $arrUserSummary -ReportType UserSummary
        }
        if ($arrNotUsingSkype){
            Write-Verbose -Message "Exporting report for $($arrNotUsingSkype.Count) users who haven't signed into Skype for Business in the past $NumberOfDaysToSearch days."
            Export-CxdData -DataInput $arrNotUsingSkype -ReportType NotUsingSkype
        }
        if ($arrUserFeedback){
            $arrUserFeedback = $arrUserFeedback | Where-Object {$_}
            Write-Verbose -Message "Exporting Rate My Call feedback report."
            Export-CxdData -DataInput $arrUserFeedback -ReportType UserFeedback
        }
        if ($arrClientVersionsScrubbed){
            #$arrClientVersionsScrubbed.Version | ProcessClientVersions
            Write-Verbose -Message "Exporting client version report."
            Export-CxdData -DataInput $arrClientVersionsScrubbed -ReportType ClientVersions
        }
        if ($arrFailedCalls){
            Write-Verbose -Message "Exporting failed calls report."
            Export-CxdData -DataInput $arrFailedCalls -ReportType FailedCalls
        }
    }

    end{}
}
function ProcessUserSummary{
    [cmdletbinding()]
        Param(
            [Parameter(mandatory=$true, valuefrompipeline=$false)]
            $userSummaryInput,
            [Parameter(mandatory=$true, valuefrompipeline=$false)]
            $UserPrincipalName        
        )
    begin{}
    process{
        #[array]$objFeedback = $_QoeReport.FeedBackReports | Where-Object FromUserUri -eq $userI.UserPrincipalName #to use as count and other variable definitions
        [int]$intFeedbackTotal = ($userSummaryInput.qoereport | Where-Object FeedbackReports).count
        [int]$intFeedbackAvoided = ($userSummaryInput.QoEReport.FeedbackReports | Where-Object {$_.Rating -like "0*"}).Count #feedback requested but not submitted by the user
        [int]$intFeedbackPoor = ($userSummaryInput.QoEReport.FeedBackReports | Where-Object {$_.Rating -like "1*" -or $_.Rating -like "2*"}).Count #a 1 or a 2 is considered 'poor' feedback in SFBO
        [int]$intFeedbackGood = $intFeedbackTotal - $intFeedbackAvoided - $intFeedbackPoor
        [int]$intFeedbackProvided = $intFeedbackTotal - $intFeedbackAvoided

        if ($intFeedbackProvided -eq "0"){
            $feedbackPercentage = $intFeedbackProvided.ToString("P")
            $feedbackPoorPercentage = $intFeedbackProvided.ToString("P")
        }else{
            $feedbackPercentage = ($intFeedbackProvided / $intFeedbackTotal).ToString("P")
            $feedbackPoorPercentage = ($intFeedbackPoor / $intFeedbackProvided).ToString("P")
        }

        [array]$userSummary = [PSCustomObject][ordered]@{
            UserPrincipalName = $userI.UserPrincipalName
            AudioSessions = $userSummaryInput.Count
            FeedbackTotal = $intFeedbackTotal
            FeedbackGiven = $intFeedbackProvided
            FeedbackGood = $intFeedbackGood
            FeedbackAvoided = $intFeedbackAvoided
            FeedbackPoor = $intFeedbackPoor
            FeedbackPercentage = $feedbackPercentage
            FeedbackPoorPercentage = $feedbackPoorPercentage
            LastLogon = $objLastLogon.StartTime
        }
        return $userSummary
    }
    end{}
}

function ProcessFailedCalls{
    begin{}
    process{
        #pull out matching diagnostic codes
        #need to account for multiple objects in the ErrorReports and choose the first one otherwise, accept the default
            if ($_.ErrorReports.Count -gt "1"){
                $requestType = $_.ErrorReports.RequestType[0]
                $diagnosticId = $_.ErrorReports.DiagnosticId[0]
                $diagnosticHeader = $_.ErrorReports.DiagnosticHeader[0]
            }else{
                $requestType = $_.ErrorReports.RequestType
                $diagnosticId = $_.ErrorReports.DiagnosticId
                $diagnosticHeader = $_.ErrorReports.DiagnosticHeader
            }
            #$test = [regex]::Match($diagnosticHeader, '(StatusString:.+?)\;')
            #$test2 = [regex]::Match($diagnosticHeader, '(Reason:.+?)\;')
            [array]$newObject = [PSCustomObject][ordered]@{
                FromUri = $_.FromUri
                ToUri = $_.ToUri
                StartTime = $_.StartTime
                EndTime = $_.EndTime
                CallDurationInSeconds = $(if ($_.EndTime){($_.EndTime - $_.StartTime).TotalSeconds}else{"N/A"})
                MediaType = $_.MediaTypesDescription
                ConferenceUrl = $(if ($_.ConferenceUrl){$_.ConferenceUrl}else{"N/A"})
                RequestType = $requestType
                DiagnosticId = $diagnosticId
                FromClientVersion = $_.FromClientVersion
                ToClientVersion = $_.ToClientVersion
                DiagnosticHeader = $diagnosticHeader
                DialogId = $_.DialogId
            }

        return $newObject
    }
    end{}
}
function Set-CxdSavePath{
        begin{}
        process{
            if (!(Test-Path -Path $ReportSavePath)){
                try{
                    Write-Verbose "Creating directory $ReportSavePath."
                    mkdir -Path $ReportSavePath | Out-Null
                }catch{
                    throw;
                }
            }
        }
        end{}
}

function Export-CxdData{
    
    [cmdletbinding()]
    Param
    (
        [Parameter(mandatory=$true, valuefrompipeline=$false)]
        [PSObject]$DataInput,
        
        [Parameter(mandatory=$true, valuefrompipeline=$false)]
        [string]$ReportType
    )

    begin{}
    process{
        try{
            $dataInput | ConvertTo-Html | Out-File -FilePath ($ReportSavePath + ('\SFB-' + $reportType + '-{0:u}.html' -f (Get-Date)).Replace(':','-'))
            $dataInput | Export-Csv -Path ($ReportSavePath + ('\SFB-' + $reportType + '-{0:u}.csv' -f (Get-Date)).Replace(':','-')) -NoTypeInformation
        }catch{
            throw
        }
    }
    end{}

}

function Get-OfficeVersionData{

    <##############################
    #.SYNOPSIS
    #Retrieves HTML data by accessing public web sites containing Office versions, then parsing HTML into a PSObject.
    #
    #.DESCRIPTION
    #We use this internal function to find the table containing the Office version so we can compare it with the user-agent version data in Get-CsUserSession.
    #
    #.EXAMPLE
    #Get-OfficeVersionData -OfficeVersion 2016 -InstallType C2R -Tag Table -Id 99867asdfg11234r
    #
    #.NOTES
    #The HTML tag and id used to find the right table data may change over time however we'll do our best to maintain this module with the right URI/tag/id fields.
    ##############################>


    [cmdletbinding()]
        Param
        (
        [Parameter(Mandatory=$true)]
        [ValidateSet("2016","2013")]
        [string]$OfficeVersion,

        [Parameter(Mandatory=$true)]
        [ValidateSet("C2R","MSI")]
        [string]$InstallType,

        [Parameter(Mandatory=$true)]
        [string]$Tag,
        
        [Parameter(Mandatory=$true)]
        [string]$Id
        )

    begin{
        switch ($OfficeVersion) {
            2016 {
                if ($InstallType -eq "C2R"){
                    $Uri = "https://support.office.com/en-us/article/Version-and-build-numbers-of-update-channel-releases-ae942449-1fca-4484-898b-a933ea23def7?ui=en-US&rs=en-US&ad=US#"
                }else{
                    $Uri = ""
                }
            }
            2013 {
                if ($InstallType -eq "C2R"){
                    $Uri = ""
                }

            }
        }
    }

    process{
        $webRequest = Invoke-WebRequest -Uri $Uri #initiate web request to URI
        $webObject = @($webRequest.ParsedHtml.getElementsByTagName($tag) | Where-Object id -eq $Id) #find the table matching the parameters given
        $rows = @($webObject.Rows) #extract rows
        $titles = @()
        $skipValueAdd = $null
        $objResult = $null

        foreach($row in $rows){
            $cells = @($row.Cells)
            $resultObject = [Ordered]@{}

            if ($row.rowIndex -eq "0"){
                $titles = @($cells | ForEach-Object {"" + ($_.innerText).Trim()})
                $skipValueAdd = $true #necessary to stop the first row from being values in the first index of the array
            }
        
            for ($counter = 0; $counter -lt $cells.Count; $counter++){
                $title = $titles[$counter]
                $resultObject[$title] = ("" + $cells[$counter].innerText).trim()
            }
            if (!$skipValueAdd){
                [PSCustomObject]$resultObject
                [array][pscustomobject]$objResult += $resultObject
            }
            $skipValueAdd = $null #reset value to add proper rows
        }

        
    }
    end{}
}
function Invoke-CxdSkypeOnlineConnection{
    [cmdletbinding()]
    Param
    (
    [Parameter(mandatory=$false, valuefrompipeline=$false)]
    [switch]$RepairPSSession
    )
    begin{}
    process{
        #determine if Skype for Business PsSession is loaded in memory
        $sessionInfo = Get-PsSession

        #calculate session time
        if ($global:sessionStartTime){
            $global:sessionTotalTime = ((Get-Date) - $global:sessionStartTime)
        }
        
        #need to loop through each session a user might have opened previously
        foreach ($sessionItem in $sessionInfo){
            #check session timer to know if we need to break the connection in advance of a timeout. Break and make new after 40 minutes.
            if ($sessionItem.ComputerName.Contains(".online.lync.com") -and $sessionItem.State -eq "Opened" -and $global:sessionTotalTime.TotalSeconds -ge "2400"){
                Write-Verbose -Message "The PowerShell session has been running for $($global:sessionTotalTime.TotalMinutes) minutes. We need to shut it down and create a new session due to the access token expiration at 60 minutes."
                $sessionItem | Remove-PSSession
                Start-Sleep -Seconds 3
                $strSessionFound = $false
                $global:sessionTotalTime = $null #reset the timer
            }

            #try to repair PSSession
            if ($sessionItem.ComputerName.Contains(".online.lync.com") -and $sessionItem.State -ne "Opened" -and $RepairPSSession){
                Write-Verbose -Message "Attempting to repair broken PowerShell session to Skype for Business Online using cached credential."
                $sessionItem | Remove-PSSession
                Start-Sleep -Seconds 3
                $strSessionFound = $false
                $global:sessionTotalTime = $null
            }elseif ($sessionItem.ComputerName.Contains(".online.lync.com") -and $sessionItem.State -eq "Opened"){
                $strSessionFound = $true
            }
        }

        if (!$strSessionFound){
            Write-Verbose -Message "Creating new Skype Online PowerShell session..."
            try{
                if ($OverrideAdminDomain){
                    #import to global scope
                    $lyncsession = New-CsOnlineSession -Credential $credential -OverrideAdminDomain $OverrideAdminDomain -ErrorAction SilentlyContinue -ErrorVariable $newOnlineSessionError
                }else{
                    $lyncsession = New-CsOnlineSession -Credential $credential -ErrorAction SilentlyContinue -ErrorVariable $newOnlineSessionError
                }
                
            }catch{
                throw;
            }
            if ($newOnlineSessionError){
                throw;
            }
            Write-Verbose -Message "Importing remote PowerShell session..."
            $global:sessionStartTime = (Get-Date)
            Import-PSSession $lyncsession -AllowClobber | Out-Null
        }
    }
    end{}
}
function Get-CxdSkypeOnlineUsers{
    begin{}
    process{
        if ($CsvFileWithUsers){
            if ($(Test-Path -Path $CsvFileWithUsers)){
                #user specified a CSV file to import users and the file exists
                Write-Verbose -Message "Processing users from CSV file."
                $enabledUsers = Import-Csv $CsvFileWithUsers
                #check CSV to make sure we have the right header
                if (($enabledUsers | Get-Member | ForEach-Object {$_.Name -eq "UserPrincipalName"} | Where-Object {$_ -eq $True}).count -eq "0"){
                    Write-Error -Message "The CSV file you've specified does not contain the correct header value of 'UserPrincipalName'. Please correct this and run this function again."
                    exit
                }elseif(($enabledUsers | ForEach-Object {[bool]($_.UserPrincipalName -as [System.Net.Mail.MailAddress])} | Where-Object {$_ -eq $False}).count -ge "1"){
                    #pretty cool way of determining if the contents are correclty formatted as an email address!
                    Write-Error -Message "The CSV file you've specified contains an improperly formatted UserPrincipalName in one or more rows. Please correct this and run the function again."
                    exit
                }
                Write-Verbose -Message  "Please wait while we get all enabled users from the CSV file..."
                $enabledUsers = $enabledUsers | ForEach-Object UserPrincipalName | Get-CsOnlineUser -ErrorAction SilentlyContinue -WarningAction SilentlyContinue
                return $enabledUsers
            

            }else{
                #user specified a CSV but we couldn't find the file
                Write-Error -Message "The file $CsvFileWithUsers was not found."
                throw;
            }
        }else{
            #user didn't specify CSV input so we need to get all users from the tenant but warn them of the data processing time
            Write-Verbose -Message "Please wait while we get all enabled users in Skype for Business Online..."
            $enabledUsers = Get-CsOnlineUser -Filter {Enabled -eq $True} -ErrorAction SilentlyContinue -WarningAction SilentlyContinue
            Return $enabledUsers
        }
    }
    end{}
}