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
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391

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)
        -Failed calls data
        -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,jason.shave@microsoft.com
 
        or
 
        Userprincipalname
        jassha@microsoft.com
 
        or
 
        Userprincipalname
        Shave, Jason
 
 
        .EXAMPLE
 
        Get-CxdCallData -StartTime (Get-Date).AddDays(-30) -EndTime (Get-Date) -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 (jason.shave@microsoft.com)
    #>


    [cmdletbinding()]
        Param (

            [Parameter(ParameterSetName="all",Mandatory=$true)][datetime]$StartTime,
            [Parameter(ParameterSetName="all",Mandatory=$true)][datetime]$EndTime,
            [Parameter(ParameterSetName="all",Mandatory=$true)][string]$ReportSavePath,

            [Parameter(ParameterSetName="all",Mandatory=$false)][string]$OverrideAdminDomain,
            [Parameter(ParameterSetName="all",Mandatory=$false)][PSCredential]$Credential,

            [Parameter(ParameterSetName="all")]
            [Parameter(ParameterSetName="csvUsers",Mandatory=$false)][string]$CsvFileWithUsers,

            [Parameter(ParameterSetName="all")]
            [Parameter(ParameterSetName="userSearch",Mandatory=$false)][string]$UserToSearch,

            [Parameter(ParameterSetName="all")]
            [Parameter(ParameterSetName="csvUsers")]
            [Parameter(ParameterSetName="userSearch")]
            [Parameter(ParameterSetName="subnetcsv",Mandatory=$false)]$SubnetCsvFile

        )

        begin {

            try {
            
                Set-WinRMNetworkDelayMS -value "60000" -WarningAction SilentlyContinue -ErrorAction SilentlyContinue -ErrorVariable WinRMError

            } catch {

                Write-Warning -Message "Unable to set the WinRM Network Delay. This may be due to User Account Control settings. If you're not encountering timeouts you can safely ignore this warning, otherwise try running the script as an elevated user (Administrator)."

            }

            Write-Output "Check out https://github.com/jasonshave/cxdcalldata for the latest readme and opportunity to improve this module. Community contribution has made this module considerably better so thanks to everyone who has contributed!"

        }

        process {

            $global:sessionStartTime = $null
            $numBuckets = 0
            $numUsers = 0
            $enabledUsers = $null
            $arrNotUsingSkype = $null

            if (!$Credential){

                $Credential = Get-Credential -Message "Authenticate to Skype for Business Online"

            }
            #create initial SFBO Connection
            Invoke-CxdSkypeOnlineConnection

            #define the save path for reports
            $ReportSavePath = Set-CxdSavePath
            
            #process user CSV file to strip out invalid entries and make sure formatting is correct
            if ($CsvFileWithUsers){
                $csvValidatedUsers = ProcessCsv
            }

            if ($SubnetCsvFile) {
                $subnetCsvData = ProcessSubnetCsv
            }

            try{
                [array]$enabledUsers = ProcessSkypeOnlineUsers 
            }catch{
                Write-Warning -Message "Exception encountered while getting users. Attempting to remove the PowerShell PSSession and will retry..."
                Invoke-CxdSkypeOnlineConnection -RepairPSSession
                [array]$enabledUsers = ProcessSkypeOnlineUsers
            }
            
            #exit if no users to process
            if (!$enabledUsers.Count){
                Write-Warning -Message "We didn't find any users matching your query. Exiting..."
                break
            }

            #get all tenant domains to help parse federated communications report
            $tenantDomains = Get-CsTenant | Select-Object DomainUrlMap
            $tenantDomains = $tenantDomains.DomainUrlMap | Foreach-Object {"*" + $_ + "*"}
            $tenantDomains += "*.lync.com*"
            
            #calculate users and buckets
            $userTotal = $enabledUsers.Count
            $userBuckets = [math]::Ceiling($userTotal /10)
            $arrUserBuckets = @{}

            #create users and put them into buckets
            Write-Verbose -Message "Putting $($enabledUsers.Count) users into buckets..."
            $count = 0
            $enabledUsers | ForEach-Object {
                $arrUserBuckets[$count % $userBuckets] += @($_)
                $count++
            }
            Write-Verbose -Message "Placed $($enabledUsers.Count) users into $($arrUserBuckets.Count) bucket(s)."

            #process all discovered users into buckets
            $pStart = Get-Date
            $arrUserBuckets | ProcessBuckets

            #process federated summary data
            FederatedCommunicationsSummary

        }
    
        end{
            Write-Verbose -Message "Removing PowerShell Session..."
            Get-PSSession | Remove-PSSession
        }   
}

function ProcessBuckets{
    [cmdletbinding()]
    Param(
        [Parameter(Mandatory=$true,ValueFromPipeline=$true)]$arrUserBuckets
    )
    begin{}
    process{
        foreach ($userItem in $arrUserBuckets.Values){

            #progress bar for total buckets
            $numBuckets++
            $bId = 1
            $bActivity = "Processing " + $enabledUsers.Count + " users in " + $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
            }

            $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

            #return session data for users in this bucket
            ProcessUsersInBuckets -userItem $userItem
        }
    }
}

function ProcessUsersInBuckets{
    [cmdletbinding()]
    Param(
        [Parameter(Mandatory=$false)]$userItem
    )
    begin{
        #reset numUsers to prevent over 100% being interpreted
        $numUsers = 0
        #before we process this bucket of users we need to check the global session timer to prevent access token expiration
        Invoke-CxdSkypeOnlineConnection
    }
    process{
        foreach($userI in $userItem){
            #set variables
            $numUsers ++
            $uId = 2
            $objLastLogon = $null
            $audioSessions = $null
            $getUserSessionError = $null
            $sipAddress = $userI.SipAddress.Replace("sip:","")
            $uActivity = "Processing users..."
            $uStatus = "Gathering user session data report for " + $sipAddress
            [int]$uPercentComplete = ($numUsers/($userItem.Count + 1)) * 100
            $uCurrentOperation = [string]$uPercentComplete + "% Complete"

            Write-Verbose -Message "Getting the past user session data for $sipAddress"
            Write-Progress -Activity $uActivity -Status $uStatus -Id $uId -PercentComplete $uPercentComplete -CurrentOperation $uCurrentOperation -ParentId $bId

            try{
                [array]$userSession = Get-AllUserSessionData -startTime $startTime -endTime $endTime -sipAddress $sipAddress
            }catch{
                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-AllUserSessionData -startTime $startTime -endTime $endTime -sipAddress $sipAddress
            }

            #MOST PROCESSING/EXPORT HAPPENS HERE#
            if ($userSession) {
                AllAudioCalls -userSession $userSession
                RateMyCallFeedback -userSession $userSession
                ClientVersions -userSession $userSession
                UserDevices -userSession $userSession
                FailedCalls -userSession $userSession
                UserSummary -userSession $userSession -UserPrincipalName $sipAddress
                
                if ($SubnetCsvFile) {
                    #build array of calls matching the given subnet
                    ProcessSubnetCalls -userSession $userSession
                }

                #need to store in global variable to use in summary report processing
                [array]$global:filteredDomainComms += FederatedCommunications -userSession $userSession
                
            } else {

                UsersNotUsingSkype -userSession $userSession -UserPrincipalName $sipAddress

            }
        }
    }
    end{}
            
}

function Get-AllUserSessionData{
    [cmdletbinding()]
    Param(
        $startTime,
        $endTime,
        $sipAddress
    )

    begin {}
    process {
        try {

            [array]$userSession = Get-CsUserSession -StartTime $startTime -EndTime $endTime -User $sipAddress -WarningAction SilentlyContinue -ErrorAction SilentlyContinue -ErrorVariable $userSessionError

        } catch {

            #there was an exception and the command did not execute
            throw $_

        } finally {

            if ($userSessionError) {

                #the command executed but returned an error
                throw $getUserSessionError

            }

        }

        #sort data by oldest to newest to check the array for the oldest call in preparation for recursion
        $userSession = $userSession | Sort-Object -Property EndTime

        #verify record count hasn't been exceeded and perform recursion if necessary to retrieve additional records
        if ($userSession.Count -ge 1000){
            $newStart = $userSession[-1].endTime
            Write-Information -Message "Found more than 1000 records for $sipAddress. Performing recursive query to obtain more data using revised start date of $newStart"
            $userSession += Get-AllUserSessionData -startTime $newStart -endTime $endTime -sipAddress $sipAddress
        }   
    }
    end {
        return $userSession
    }
}

function AllAudioCalls {
    [cmdletbinding()]
    Param(
        [Parameter()]$userSession
    )

    [array]$sessionsWithQoE = $userSession | Where-Object QoeReport
    [array]$audioCallsWithQoE = $sessionsWithQoE | Where-Object MediaTypesDescription -like "*Audio*"

    if ($audioCallsWithQoE) {

        $processedAudioCalls = $audioCallsWithQoE | ForEach-Object {ProcessCallDataIntoObject}

    }
        
    if ($processedAudioCalls) {

        Export-CxdData -DataInput $processedAudioCalls -ReportType $PSCmdlet.CommandRuntime -Append

    }

}

function ProcessCallDataIntoObject {

    try {

        $newObject += [PSCustomObject][ordered]@{
            FromUri = $_.FromUri
            ToUri = $_.ToUri
            Rating = $(if ($_.QoeReport.FeedbackReports.Count -gt 1) {$_.QoeReport.FeedBackReports.Rating[0]} else  {$_.QoeReport.FeedbackReports.Rating})
            FeedbackText = $(if ($_.QoeReport.FeedBackReports.Count -gt 1) {$_.QoeReport.FeedbackReports.FeedbackText[0]} else {$_.QoeReport.FeedbackReports.FeedbackText})
            Tokens = $(if ($_.QoeReport.FeedbackReports) {$_ | ProcessTokens})
            MediaType = $_.MediaTypesDescription
            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
            ConferenceUri = $_.QoEReport.Session.ConferenceUri
            FromVirtualizationFlag = $_.QoeReport.Session.FromVirtualizationFlag
            ToVirtualizationFlag = $_.QoeReport.Session.ToVirtualizationFlag
            FromConnectivityIce = $_.QoeReport.MediaLines.FromConnectivityIce
            FromCaptureDev = $_.QoeReport.MediaLines.FromCaptureDev
            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
            Stream1_JitterInterArrival = $_.QoeReport.AudioStreams[0].JitterInterArrival
            Stream1_JitterInterArrivalMax = $_.QoeReport.AudioStreams[0].JitterInterArrivalMax
            Stream1_PacketLossRate = $_.QoeReport.AudioStreams[0].PacketLossRate
            Stream1_PacketLossRateMax = $_.QoeReport.AudioStreams[0].PacketLossRateMax
            Stream1_BurstDensity = $_.QoeReport.AudioStreams[0].BurstDensity
            Stream1_BurstDuration = $_.QoeReport.AudioStreams[0].BurstDuration
            Stream1_BurstGapDensity = $_.QoeReport.AudioStreams[0].BurstGapDensity
            Stream1_BurstGapDuration = $_.QoeReport.AudioStreams[0].BurstGapDuration
            Stream1_PayloadDescription = $_.QoeReport.AudioStreams[0].PayloadDescription
            Stream1_AudioFECUsed = $_.QoeReport.AudioStreams[0].AudioFECUsed
            Stream1_SendListenMOS = $_.QoeReport.AudioStreams[0].SendListenMOS
            Stream1_OverallAvgNetworkMOS = $_.QoeReport.AudioStreams[0].OverallAvgNetworkMOS
            Stream1_NetworkJitterMax = $_.QoeReport.AudioStreams[0].NetworkJitterMax
            Stream1_NetworkJitterAvg = $_.QoeReport.AudioStreams[0].NetworkJitterAvg
            Stream1_RoundTrip = $_.QoeReport.AudioStreams[0].RoundTrip
            Stream1_RoundTripMax = $_.QoeReport.AudioStreams[0].RoundTripMax
            Stream1_StreamDirection = $_.QoeReport.AudioStreams[0].StreamDirection
            Stream2_JitterInterArrival = $_.QoeReport.AudioStreams[1].JitterInterArrival
            Stream2_JitterInterArrivalMax = $_.QoeReport.AudioStreams[1].JitterInterArrivalMax
            Stream2_PacketLossRate = $_.QoeReport.AudioStreams[1].PacketLossRate
            Stream2_PacketLossRateMax = $_.QoeReport.AudioStreams[1].PacketLossRateMax
            Stream2_BurstDensity = $_.QoeReport.AudioStreams[1].BurstDensity
            Stream2_BurstDuration = $_.QoeReport.AudioStreams[1].BurstDuration
            Stream2_BurstGapDensity = $_.QoeReport.AudioStreams[1].BurstGapDensity
            Stream2_BurstGapDuration = $_.QoeReport.AudioStreams[1].BurstGapDuration
            Stream2_PayloadDescription = $_.QoeReport.AudioStreams[1].PayloadDescription
            Stream2_AudioFECUsed = $_.QoeReport.AudioStreams[1].AudioFECUsed
            Stream2_SendListenMOS = $_.QoeReport.AudioStreams[1].SendListenMOS
            Stream2_OverallAvgNetworkMOS = $_.QoeReport.AudioStreams[1].OverallAvgNetworkMOS
            Stream2_NetworkJitterMax = $_.QoeReport.AudioStreams[1].NetworkJitterMax
            Stream2_NetworkJitterAvg = $_.QoeReport.AudioStreams[1].NetworkJitterAvg
            Stream2_RoundTrip = $_.QoeReport.AudioStreams[1].RoundTrip
            Stream2_RoundTripMax = $_.QoeReport.AudioStreams[1].RoundTripMax
            Stream2_StreamDirection = $_.QoeReport.AudioStreams[1].StreamDirection
            TraceRoutes = $strTraceRoutes
            DialogId = $_.DialogId

        }

        return $newObject

    } catch {

        #Write-Host $_

    }

}

function ProcessSubnetCalls {
    $subnetRegex = '(?<Address>((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?))'
    #filter all sessions for just calls
    [array]$audioSessions = $userSession | Where-Object MediaTypesDescription -like "*Audio*"

    foreach ($call in $audioSessions) {
        $ipAddress = ($call.QoEReport.MediaLines | Where-Object MediaLineLabelText -eq 'main-audio').FromIPAddr
        if ($ipAddress -match $subnetRegEx) {

            $subnetMatch = SubnetMatch -inputData $Matches[0]

            if (![string]::IsNullOrEmpty($subnetMatch)) {
                #this is a match of the subnet the user provided
                $dialogId = $call.DialogId -replace ';','%3B'
                [array]$matchedSubnetForCall = [pscustomobject]@{
                    'From' = $call.FromUri
                    'To' = $call.ToUri
                    'Start Time' = $call.StartTime
                    'End Time' = $call.EndTime
                    'Dialog Id' = $call.DialogId
                    'IP Address' = $ipAddress
                    'Subnet Address' = $subnetMatch.SubnetAddress
                    'Subnet Mask' = $subnetMatch.SubnetMask
                    'Transport' = $call.QoEReport.MediaLines.Transport
                    'Jitter Inter Arrival' = $(if ($call.QoeReport.AudioStreams){$call.QoeReport.AudioStreams[0].JitterInterArrival}else{"N/A"})
                    'Jitter Inter Arrival Max' = $(if ($call.QoeReport.AudioStreams){$call.QoeReport.AudioStreams[0].JitterInterArrivalMax}else{"N/A"})
                    'Packet Loss Rate' = $(if ($call.QoeReport.AudioStreams){$call.QoeReport.AudioStreams[0].PacketLossRate}else{"N/A"})
                    'Packet Loss Rate Max' = $(if ($call.QoeReport.AudioStreams){$call.QoeReport.AudioStreams[0].PacketLossRateMax}else{"N/A"})
                    'Burst Density' = $(if ($call.QoeReport.AudioStreams){$call.QoeReport.AudioStreams[0].BurstDensity}else{"N/A"})
                    'Burst Duration' = $(if ($call.QoeReport.AudioStreams){$call.QoeReport.AudioStreams[0].BurstDuration}else{"N/A"})
                    'Burst Gap Density' = $(if ($call.QoeReport.AudioStreams){$call.QoeReport.AudioStreams[0].BurstGapDensity}else{"N/A"})
                    'Burst Gap Duration' = $(if ($call.QoeReport.AudioStreams){$call.QoeReport.AudioStreams[0].BurstGapDuration}else{"N/A"})
                    'Payload Description' = $(if ($call.QoeReport.AudioStreams){$call.QoeReport.AudioStreams[0].PayloadDescription}else{"N/A"})
                    'Audio FEC Used' = $(if ($call.QoeReport.AudioStreams){$call.QoeReport.AudioStreams[0].AudioFECUsed}else{"N/A"})
                    'Send Listen MOS' = $(if ($call.QoeReport.AudioStreams){$call.QoeReport.AudioStreams[0].SendListenMOS}else{"N/A"})
                    'Overall Avg Network MOS' = $(if ($call.QoeReport.AudioStreams){$call.QoeReport.AudioStreams[0].OverallAvgNetworkMOS}else{"N/A"})
                    'Network Jitter Max' = $(if ($call.QoeReport.AudioStreams){$call.QoeReport.AudioStreams[0].NetworkJitterMax}else{"N/A"})
                    'Network Jitter Avg' = $(if ($call.QoeReport.AudioStreams){$call.QoeReport.AudioStreams[0].NetworkJitterAvg}else{"N/A"})
                    'Stream Direction' = $(if ($call.QoeReport.AudioStreams){$call.QoeReport.AudioStreams[0].StreamDirection}else{"N/A"})
                    'Trace Routes' = $strTraceRoutes
                    'Call Analytics' = 'https://adminportal.services.skypeforbusiness.com/analytics/user/' + $sipAddress + '/call/' + $dialogId
                }

                #export this item
                Export-CxdData -DataInput $matchedSubnetForCall -ReportType ProcessSubnetCalls
            }
        }
    }
}

function RateMyCallFeedback {
    [cmdletbinding()]
    Param(
        [Parameter()]$userSession
    )

    begin {}
    process {

        [array]$audioSessions = $userSession | Where-Object MediaTypesDescription -like "*Audio*"
        [array]$processedFeedback = $audioSessions | Where-Object {$_.QoeReport.FeedbackReports} | ProcessFeedback

    }
    end {

        if ($processedFeedback) {

            Export-CxdData -DataInput $processedFeedback -ReportType $PSCmdlet.CommandRuntime -Append
            
        }
    }
}


function UserDevices{
    [cmdletbinding()]
    Param(
        [Parameter()]$userSession
    )

    begin {}
    process {
        [array]$audioSessions = $userSession | Where-Object MediaTypesDescription -like "*Audio*"
        [array]$userDevices = $audioSessions | ProcessUserDevices
    }
    end {
        if ($userDevices){
            Export-CxdData -DataInput $userDevices -ReportType $PSCmdlet.CommandRuntime -Append
        }
    }
}

function FailedCalls{
    [cmdletbinding()]
    Param(
        [Parameter()]$userSession
    )

    begin {}
    process {
        [array]$failedCalls = $audioSessions | Where-Object {$_.ErrorReports.ErrorCategory -eq "UnexpectedFailure"} | ProcessFailedCalls
    }
    end {
        if ($failedCalls){
            Export-CxdData -DataInput $failedCalls -ReportType $PSCmdlet.CommandRuntime -Append
        }
    }
}

function UserSummary{
    [cmdletbinding()]
    Param(
        [Parameter()]$userSession,
        [Parameter()]$UserPrincipalName
    )

    begin {}
    process {
        [array]$audioSessions = $userSession | Where-Object MediaTypesDescription -like "*Audio*"
        [array]$userSummary = ProcessUserSummary -userSummaryInput $audioSessions -UserPrincipalName $UserPrincipalName
    }
    end {
        if ($userSummary){
            Export-CxdData -DataInput $userSummary -ReportType $PSCmdlet.CommandRuntime -Append
        }
    }
}

function FederatedCommunications{
    [cmdletbinding()]
    Param
    (
    [Parameter()]$userSession
    )

    begin {}
    process {
        if ($userSession){
            #gather session information for filtering
            $arrDomainComms = $userSession | Where-Object MediaTypesDescription -ne "[RegisterEvent]" | Select-Object StartTime,EndTime,FromUri,ToUri,MediaTypesDescription,DialogId
            
            #filter out internal to internal communications and remove duplicates
            $domainFilterResult = FilterInternalDomainData -DomainData $arrDomainComms -TenantDomains $tenantDomains -FilterOutFromTo | Select-Object StartTime,EndTime,FromUri,ToUri,MediaTypesDescription -Unique | Where-Object MediaTypesDescription -ne ""
        }
    }
    end {
        if ($domainFilterResult){
            Export-CxdData -DataInput $domainFilterResult -ReportType $PSCmdlet.CommandRuntime -Append
            return $domainFilterResult
        }
        
    }
}

function FederatedCommunicationsSummary{
    [cmdletbinding()]
    Param()

    begin {}
    process {
        #process Federated Domain Summary data
        $objProcessedDomainData = $filteredDomainComms | ProcessDomainCallData
        $objFromDomain = $objProcessedDomainData.FromDomain | Select-Object -Unique
        $objToDomain = $objProcessedDomainData.ToDomain | Select-Object -Unique
        $objAllDomains = $objFromDomain + $objToDomain
        $objFilteredDomains = FilterInternalDomainData -TenantDomains $tenantDomains -DomainData $objAllDomains -FilterOutDomains:$true
        
        $arrFederatedStats = ProcessFederatedData -FederatedComms $filteredDomainComms -FilteredDomains $objFilteredDomains
    }
    end {
        if ($arrFederatedStats){
            Export-CxdData -DataInput $arrFederatedStats -ReportType $PSCmdlet.CommandRuntime -Append
        }
    }
}

function ClientVersions{
    [cmdletbinding()]
    Param(
        [Parameter()]$userSession
    )
    begin{
 
    }
    process{    
        $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 ""
        $clientVersions = $clientVersions | Select-Object @{Name="User";Expression={$userI.UserPrincipalName}},@{Name="Version";Expression={$_.Version}} -Unique           
    }
    end{
        if ($clientVersions){
            Export-CxdData -DataInput $clientVersions -ReportType $PSCmdlet.CommandRuntime -Append
        }
    }
}

function UsersNotUsingSkype{
    [cmdletbinding()]
    Param(
        [Parameter()]$userSession,
        [Parameter()]$UserPrincipalName
    )
    begin{}
    process{
        if (!$userSession){
            $usersNotUsingSkype = [PSCustomObject]@{
                UsersNotUsingSkype = $UserPrincipalName
            }
        }
    }
    end{
        if ($usersNotUsingSkype){
            Export-CxdData -DataInput $usersNotUsingSkype -ReportType $PSCmdlet.CommandRuntime -Append
        }
    }

}

function ProcessFederatedData{
    [cmdletbinding()]
    Param(
        [Parameter(Mandatory=$false)]$FederatedComms,   
        [Parameter(Mandatory=$false)]$FilteredDomains
    )
    begin{
        [array]$arrFedResult = @()
    }
    process{
        #count IM Sessions
        foreach ($domainItem in $FilteredDomains){
            $arrFilteredDomainComms = $FederatedComms | Where-Object {$_.ToUri -like "*$($domainItem)" -or $_.fromUri -like "*$($domainItem)"}
            if ($arrFilteredDomainComms){
                $arrFedResult += [PSCustomObject][ordered]@{
                    Domain = $domainItem
                    IM = ($arrFilteredDomainComms.MediaTypesDescription | Where-Object {$_ -eq "[IM]"}).Count
                    Audio = ($arrFilteredDomainComms.MediaTypesDescription | Where-Object {$_ -eq "[Audio]"}).Count
                    Video = ($arrFilteredDomainComms.MediaTypesDescription | Where-Object {$_ -eq "[Audio][Video]"}).Count
                    Sharing = ($arrFilteredDomainComms.MediaTypesDescription | Where-Object {$_ -eq "[Video][AppSharing]"}).Count
                    Conference = ($arrFilteredDomainComms.MediaTypesDescription | Where-Object {$_ -eq "[Conference]"}).Count
                    "IM Conference" = ($arrFilteredDomainComms.MediaTypesDescription | Where-Object {$_ -eq "[Conference][IM]"}).Count
                    "Sharing Conference" = ($arrFilteredDomainComms.MediaTypesDescription | Where-Object {$_ -eq "[Conference][AppSharing]"}).Count
                    "Audio Conference" = ($arrFilteredDomainComms.MediaTypesDescription | Where-Object {$_ -eq "[Conference][Audio]"}).Count
                    "Video Conference" = ($arrFilteredDomainComms.MediaTypesDescription | Where-Object {$_ -eq "[Conference][Audio][Video]"}).Count
                }
            }
        }

    }
    end{
        return $arrFedResult
    }
}

function FilterInternalDomainData{
    [cmdletbinding()]
    Param(
        [Parameter(Mandatory=$false)][array]$TenantDomains,
        [Parameter(Mandatory=$false)]$DomainData,
        [Parameter(Mandatory=$false)][switch]$FilterOutFromTo,
        [Parameter(Mandatory=$false)][switch]$FilterOutDomains
    )
    begin{}
    process{
        #removes objects where to/from are considered internal to the organization
        if($FilterOutFromTo){
            ForEach ($domainItem in $TenantDomains){
                $DomainData = $DomainData | Where-Object {$_.ToUri -and $_.FromUri -notlike $domainItem}
            }
        return $DomainData
        }

        #removes Domain values from the object
        if($FilterOutDomains){
            ForEach ($domainItem in $TenantDomains){
                $DomainData = $DomainData | Where-Object {$_ -notlike $domainItem}
            }
        return $DomainData
        }

    }
    end{}
}

function ProcessDomainCallData{
    [cmdletbinding()]
    Param
    (
    [Parameter(Mandatory=$false,ValueFromPipeline=$true)]
    [object]$Calls
    )
    begin{

    }
    process{
        if (!$calls){
            return
        }
        $tempSplitFrom = $_.FromUri.Split("@")
        $strFromDomain = $tempSplitFrom[1]
        $tempSplitTo = $_.ToUri.Split("@")
        $strToDomain = $tempSplitTo[1]

        $newObject = [PSCustomObject][ordered]@{
            FromUri = $_.FromUri
            ToUri = $_.ToUri
            FromDomain = $strFromDomain
            ToDomain = $strToDomain
            MediaType = $_.MediaTypesDescription
        }

        return $newObject
    }
    end{}
}

function ProcessUserDevices{
    begin{
        [regex]$devicesToExclude = "(Default output device)|(Default input device)|(Remote Audio)|(Built-in Output)"
    }
    process{
        #if no QoE report exists; exit
        if (!$_.QoeReport){return}

        $audioMediaLines = $null
        $toUriSessions = $null
        $fromUriSessions = $null
        $newFromObject = $null
        $newToObject = $null
        
        #break down MediaLines as this can be an array (i.e. multi-part video gives back an array of objects)
        $audioMediaLines = $_.QoEReport.MediaLines | ForEach-Object {$_ | Where-Object MediaLineLabelText -eq "main-audio"}
        
        #get all sessions where the target user matches the called party
        [array]$toUriSessions = $_ | Where-Object {$_.ToUri -eq $UserI.UserPrincipalName}
        
        #get all sessions where the target user matches the calling party
        [array]$fromUriSessions = $_ | Where-Object {$_.FromUri -eq $UserI.UserPrincipalName}# -and $audioMediaLines.FromRenderDev -match $devicesToExclude}

        $newFromObject = [PSCustomObject][ordered]@{
            SipAddress = $fromUriSessions.FromUri
            RenderDevice = $(if ($audioMediaLines.FromRenderDev -match $devicesToExclude -or $audioMediaLines.FromRenderDev -eq ""){$null}else{$audioMediaLines.FromRenderDev})
        }
        $newToObject = [PSCustomObject][ordered]@{
            SipAddress = $ToUriSessions.ToUri
            RenderDevice = $(if ($audioMediaLines.ToRenderDev -match $devicesToExclude -or $audioMediaLines.ToRenderDev -eq ""){$null}else{$audioMediaLines.ToRenderDev})
        }
        
        if ($newFromObject.RenderDevice -and $newFromObject.SipAddress){return $newFromObject}
        if ($newToObject.RenderDevice -and $newFromObject.SipAddress){return $newToObject}
            
    }
    end{}
}

function ProcessTokens {
    [cmdletbinding()]
    param(
        [parameter(ValueFromPipeline)]$_
    )

    process {
        #we may have two feedbackreports (array) to handle

        [array]$arrTokens = ($_.QoeReport.FeedbackReports | Where-Object FromUserUri -eq $sipAddress | Select-Object Tokens).Tokens | Where-Object Value -ne 0

        if (!$arrTokens) {

            $arrTokens = "No specific feedback selected."
            return $arrTokens

        }

        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 = $arrTokens.Id

        }

        return $arrTokens
    }
}

function ProcessFeedback {
    [cmdletbinding()]
    Param(
        [Parameter(ValueFromPipeline)]$_
    )

    if (!$_.QoeReport.FeedbackReports) {

        #no feedback report found

    } else {

        #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

    }

}

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 Call
        Object containing the call properties used to build the string we return.
         
        .EXAMPLE
        ProcessTraceRoutes -Call <object>
 
    #>


    [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 ProcessUserSummary{
    [cmdletbinding()]
        Param(
            [Parameter()]$userSummaryInput,
            [Parameter()]$UserPrincipalName        
        )
    begin{}
    process{
        [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
            AudioOnlySessions = ($userSummaryInput | Where-Object MediaTypesDescription -eq "[Audio]").Count
            ConferenceSessions = ($userSummaryInput | Where-Object MediaTypesDescription -like "*[Conference]*").Count
            SessionsWithVideo = ($userSummaryInput | Where-Object MediaTypesDescription -like "*[Video]*").Count
            FeedbackTotal = $intFeedbackTotal
            FeedbackGiven = $intFeedbackProvided
            FeedbackGood = $intFeedbackGood
            FeedbackAvoided = $intFeedbackAvoided
            FeedbackPoor = $intFeedbackPoor
            FeedbackPercentage = $feedbackPercentage
            FeedbackPoorPercentage = $feedbackPoorPercentage
        }
        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{
    [cmdletbinding()]
    Param(
        #[Parameter(Mandatory=$false)]$KeepExistingReports
    )

        begin{
            #trim trailing backslash in case user entered it
            $ReportSavePath = $ReportSavePath.TrimEnd("\")
        }
        process{
            #create directory
            if (!(Test-Path -Path $ReportSavePath)){
                try{
                    Write-Verbose "Attempting to create base report path: $ReportSavePath"
                    mkdir -Path $ReportSavePath | Out-Null
                }catch{
                    throw
                }
            }

            #create unique folder for test results
            $folderDate = Get-Date -UFormat "%Y-%m-%d"
            [int]$folderCounter = 0
            do {
                $folderCounter ++
                [string]$newSavePath = $ReportSavePath + "\" + $folderDate + "-" + $folderCounter
                Write-Verbose -Message "Testing save path: $newSavePath"
            }until(!(Test-Path -Path $newSavePath))

            try{
                Write-Verbose -Message "Attempting to create unique testing directory: $newSavePath"
                mkdir -Path $newSavePath | Out-Null
            }catch{
                throw
            }            
        }
        end{
            return $newSavePath
        }
}

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

    try{
        $dataInput | Export-Csv -Path ($ReportSavePath + "\" + ($reportType + ".csv")) -NoTypeInformation -Append
    }catch{
        throw
    }

}

function Invoke-CxdSkypeOnlineConnection{
    [cmdletbinding()]
    Param
    (
    [Parameter(mandatory=$false, valuefrompipeline=$false)]
    [switch]$RepairPSSession
    )
    begin{}
    process{
        #calculate session timer to handle access token expiration
        if ($global:sessionStartTime){
            $global:sessionTotalTime = ((Get-Date) - $global:sessionStartTime)
        }

        #determine if Skype for Business PsSession is loaded in memory
        $sessionInfo = Get-PsSession

        #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 2
                $SessionFound = $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
                $SessionFound = $false
                $global:sessionTotalTime = $null

            } elseif ($sessionItem.ComputerName.Contains(".online.lync.com") -and $sessionItem.State -eq "Opened"){
                Write-Verbose -Message "The PowerShell session has been running for $($global:sessionTotalTime.TotalMinutes) minutes."
                $SessionFound = $true
            }
        }

        if (!$SessionFound) {

            Write-Verbose -Message "Creating new Skype Online PowerShell session..."
            
            try {

                if ($OverrideAdminDomain) {

                    $lyncsession = New-CsOnlineSession -Credential $Credential -OverrideAdminDomain $OverrideAdminDomain -ErrorAction SilentlyContinue -ErrorVariable $newOnlineSessionError

                } else {

                    $lyncsession = New-CsOnlineSession -Credential $Credential -ErrorAction SilentlyContinue -ErrorVariable $newOnlineSessionError

                }

            } catch {

                throw;

            } finally {

                if ($newOnlineSessionError) {

                    throw $newOnlineSessionError

                }
            }

            Write-Verbose -Message "Importing remote PowerShell session..."
            $global:sessionStartTime = (Get-Date)
            Import-PSSession $lyncsession -AllowClobber | Out-Null
        }
    }
    end{}
}

function ProcessCsv{
    if (!$(Test-Path -Path $CsvFileWithUsers)){
        Write-Error -Message "The file $CsvFileWithUsers cannot be found."
        throw;
    }
        Write-Verbose -Message "Processing users from CSV file."
    try{

        $csvUsers = Import-Csv $CsvFileWithUsers

    } catch {

        throw;

    }
    #check CSV to make sure we have the right header
    if (($csvUsers | 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."
        throw;
    }elseif(($csvUsers | ForEach-Object {[bool]($_.UserPrincipalName -as [System.Net.Mail.MailAddress])} | Where-Object {$_ -eq $False}).count -ge "1"){
        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."
        throw;
    }
    return $csvUsers
}

function ProcessSkypeOnlineUsers{

    process{
        if ($UserToSearch) {
            Write-Verbose -Message "Please wait while we get data for $UserToSearch"
            return Get-CsOnlineUser -Identity $UserToSearch -ErrorAction SilentlyContinue
        }

        if ($csvValidatedUsers) {
            Write-Verbose -Message "Please wait while we find all users in Skype for Business Online using the CSV file provided."
            $enabledUsers = $csvValidatedUsers | ForEach-Object UserPrincipalName | Get-CsOnlineUser -ErrorAction SilentlyContinue -WarningAction SilentlyContinue
            return $enabledUsers
        } else {
            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
        }
    }
}

function Set-WinRMNetworkDelayMS{
    <#
    .SYNOPSIS
    Changes the WinRM setting for the NetworkDelayms property (WSMan:\localhost\Client\NetworkDelayms).
 
    .Description
    The Skype For Business Online Connector connects to Skype For Business Remote PowerShell Server in order to establish a remote session. Sometimes this remote session can be broken because of network delay. To help address this problem, Skype For Business recommends setting NetworkDelayms to 30000 milliseconds (30 seconds) instead of the default value of 5000 milliseconds (5 seconds).
 
    .Parameter value
 
    Value of the NetworkDelayms property in milliseconds (there are 1000 milliseconds in each second). This must be an integer value.
 
    .EXAMPLE
    Set-WinRMNetworkDelayMS 30000
 
    This example sets the NetworkDelayms property (WSMan:\localhost\Client\NetworkDelayms) to 30000 milliseconds (30 seconds).
 
    #>


  param(
    [Parameter(Mandatory = $false)] [string] $value="30000"
  )

  $networkDelay = Get-Item WSMan:\localhost\Client\NetworkDelayms

  if($networkDelay -eq $null)
  {
    # If cannot get NetworkDelayms due to permission or other reason, just return.
    return
  }

  $oldValue = $networkDelay.Value
  $newValue = $value

  if($newValue -ne $oldValue)
  {
    Set-Item WSMan:\localhost\Client\NetworkDelayms $newValue

    # Warns the user that running this command has changed their client setting.
    Write-Warning "WSMan NetworkDelayms has been set to $newValue milliseconds. The previous value was $oldValue milliseconds."
    Write-Warning "To improve the performance of the Skype For Business Online Connector, it is recommended that the network delay be set to 30000 milliseconds (30 seconds). However, you can use Set-WinRMNetworkDelayMS to change the network delay to any integer value."
  }
}

function SubnetMatch {
    #inherits variables from main function
    [CmdletBinding()]
    param(
        [parameter(mandatory=$true)][Net.IPAddress]$inputData
    )

    $subnetCsvData | ForEach-Object {
        if ((([Net.IPAddress]$_.subnetAddress).Address -band ([Net.IPAddress]$_.subnetMask).Address) -eq ($inputData.Address -band ([Net.IPAddress]$_.subnetMask).Address)) {
            return $_;
        }
    }

}

function ProcessSubnetCsv {

    if (!$(Test-Path -Path $SubnetCsvFile)) {

        Write-Error -Message "The file $SubnetCsvFile cannot be found."
        throw;

    }

        Write-Verbose -Message "Processing users from $SubnetCsvFile."

    try {

        [array]$csvSubnet = Import-Csv $SubnetCsvFile
         
    } catch {

        throw;

    }

    return $csvSubnet

}

function Get-AuthUri($targetUri) {
    $response = $null
    $responseException = $null
  
    try {

        $response = Invoke-WebRequest $targetUri

    } catch {

        $responseException = $_.Exception
        $response = $_.Exception.Response

    }
  
    if ($response -eq $null) {

        throw ($resources.AuthUriAcquisitionFail -f $targetUri)

    }
  
    if ($response.StatusCode -ne 401) {

        $message = ($resources.UnexpectedResponseFromServer -f $response.StatusCode)
        throw (New-Object -TypeName System.ArgumentOutOfRangeException -ArgumentList $message, $responseException)

    }
  
    $header = $response.Headers["WWW-Authenticate"]

    if (-not $header) {

        throw $resources.CannotFindAuthHeader

    }
  
    $authUri = $null;

    if ($header -match 'authorization_uri="(.*?)"') {

        $authUri = $matches[1]
    
    } else {

        throw $resources.CannotFindUriInAuthHeader

    }
  
    $clientId = [GUID]::Empty;
    if ($header -match 'client_id="(.*?)"') {

        if ([GUID]::TryParse($matches[1], [Ref] $clientId) -eq $false) {

          throw $resources.ClientIdNotGUIDInAuthHeader

        }

    } else {

        throw $resources.CannotFindClientIdInAuthHeader

    }
  
    $appAuthInfo = New-Object PsObject -Property @{authUri=$authUri ; clientId=$clientId}
  
    return $appAuthInfo

  }