CxdCallData.psm1

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693

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{}
}