-
Notifications
You must be signed in to change notification settings - Fork 0
/
MSTeamsCQD.psm1
1289 lines (999 loc) · 37.6 KB
/
MSTeamsCQD.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
# (c)2018 Microsoft Corporation. All rights reserved. This document is provided "as-is." Information and views expressed in this document,
# including URL and other Internet Web site references, may change without notice. You bear the risk of using it.
# This document does not provide you with any legal rights to any intellectual property in any Microsoft product.
# You may copy and use this document for your internal, reference purposes. You may modify this document for your internal purposes
#
################################################
# CQD POWERSHELL ##############################
# JUSTW/SETHHA #
# QUERY CQD DIRECT FROM POWERSHELL AND EXPORT #
# #
# Modified by
# Luca Sain
################################################
# Date: 30/03/2022
# Features added
# added UNION filter to perform more advanced queries with AND/OR statements
[CmdletBinding()]
param(
# Non Dynamic params go here #
)
###############################
# BEGIN JWT DECODE FUNCTIONS #
###############################
function Convert-64String ([string]$datai) {
$datai = $datai.Replace('-', '+').Replace('_', '/')
switch ($datai.Length % 4) {
0 { break }
2 { $datai += '==' }
3 { $datai += '=' }
default { throw New-Object ArgumentException ('datai') }
}
return [System.Convert]::FromBase64String($datai)
}
#
function Decode-JWT ([string]$rawToken) {
$Tokenparts = $rawToken.Split('.');
$headers = [System.Text.Encoding]::UTF8.GetString((Convert-64String $Tokenparts[0]))
$claims = [System.Text.Encoding]::UTF8.GetString((Convert-64String $Tokenparts[1]))
$signature = (Convert-64String $Tokenparts[2])
$customObject = [pscustomobject]@{
headers = ($headers | ConvertFrom-Json)
claims = ($claims | ConvertFrom-Json)
signature = $signature
}
#Write-Verbose -Message ("JWT`r`n.headers: {0}`r`n.claims: {1}`r`n.signature: {2}`r`n" -f $headers,$claims,[System.BitConverter]::ToString($signature))
return $customObject
}
#
function Get-JWTData {
[CmdletBinding()]
param
(
# Param1 help description
[Parameter(Mandatory = $true)]
[string]$Token,
[switch]$Recurse
)
if ($Recurse) {
$decoded = [System.Text.Encoding]::UTF8.GetString([System.Convert]::FromBase64String($Token))
$DecodedJwt = Decode-JWT -rawToken $decoded
}
else {
$DecodedJwt = Decode-JWT -rawToken $Token
}
#Write-Host("Token Values") -ForegroundColor Green
#Write-Host ($DecodedJwt | Select headers,claims | ConvertTo-Json)
return $DecodedJwt
}
#############################
# END JWT DECODE FUNCTIONS #
#############################
###############################
# BEGIN AAD AUTH FUNCTIONS #
###############################
####Function to Get the JWT Token VIA OAuth
function Get-CQDToken ([string]$client_id) {
if ($CQDVer -eq "V2") {
$CQDUri = "https://cqd.lync.com/spd/"
$V2Token = $true
}
else {
$CQDUri = "https://cqd.teams.microsoft.com/spd/"
$V3Token = $true
}
Add-Type -AssemblyName System.Web
$resourceUrl = $WebResource
$redirectUrl = $CQDUri
$nonce = [guid]::NewGuid().GUID
$url = "https://login.microsoftonline.com/common/oauth2/authorize?response_type=token&redirect_uri=" +
[System.Web.HttpUtility]::UrlEncode($redirectUrl) +
"&client_id=$client_id" +
"&prompt=none" + "&nonce=$nonce" + "&resource=" + [System.Web.HttpUtility]::UrlEncode($WebResource)
Add-Type -AssemblyName System.Windows.Forms
$form = New-Object -TypeName System.Windows.Forms.Form -Property @{ Width = 440; Height = 640 }
$web = New-Object -TypeName System.Windows.Forms.WebBrowser -Property @{ Width = 420; Height = 600; Url = ($url) }
$DocComp = {
$Global:uri = $web.Url.AbsoluteUri
#Write-Host $Global:uri
if ($Global:Uri -match "error=[^&]*|access_token=[^&]*") { $form.Close() }
}
$web.ScriptErrorsSuppressed = $true
$web.Add_DocumentCompleted($DocComp)
$form.Controls.Add($web)
$form.Add_Shown({ $form.Activate() })
$form.ShowDialog() | Out-Null
$Script:TokenLifeTime = [Web.HttpUtility]::ParseQueryString(($web.Url -replace '^.*?(expires_in.+)$', '$1'))['expires_in']
#Write-Host $TokenLifeTime
$Script:Token = [Web.HttpUtility]::ParseQueryString(($web.Url -replace '^.*?(access_token.+)$', '$1'))['access_token']
# Write-Host $Token
return ('Bearer {0}' -f $Script:Token)
}
#Function to connect to CQD Via AzureAD
function Connect-CqdOnline {
if ($CQDVer -eq "V2") {
$UriVar = "https://repository.cqd.lync.com/clientconfiguration"
}
else {
$UriVar = "https://cqd.teams.microsoft.com/repository/clientconfiguration"
}
$ClientConfigUri = $UriVar
$Script:Configuration = Invoke-RestMethod -Uri $ClientConfigUri -Method Get -SessionVariable WebSession -UserAgent "CQDPowerShell V2.0"
$Script:WebResource = $Configuration.AuthLoginResource
$Script:AADBearerToken = Get-CQDToken $Configuration.AuthWebAppClientId
$Script:WebSession = $WebSession
$Script:RepositoryApiBaseUrl = $Script:Configuration.RepositoryApiBaseUrl
$WebSession.headers.Add('Authorization', $AADBearerToken)
$ProvisioningStatus = Invoke-RestMethod -Uri ('{0}tenant/provision' -f $RepositoryApiBaseUrl) -Method Get -WebSession $Script:WebSession -UserAgent "CQDPowerShell V2.0"
if ($ProvisioningStatus.Status -ne 'Provisioned') {
throw ('CQD Not Provisioned for TenantId {0}. Stopping...' -f $ProvisioningStatus.TenantId)
}
$Script:DataServiceBaseUrl = Invoke-RestMethod -Uri ('{0}tenant/dataservice' -f $Script:RepositoryApiBaseUrl) -WebSession $Script:WebSession -Method Get -UserAgent "CQDPowerShell V2.0"
}
Export-ModuleMember -Function Connect-CqdOnline
#Function to validate if token exists or is valid and unexpired
function CheckToken {
#Check to see if Token already exists
if ($Script:AADBearerToken -eq $null) {
Connect-CqdOnline
}
else {
#Check Token
$JWTDecoded = Get-JWTData $Script:Token
$JWTI = $JWTDecoded.claims.iat
$JWTE = $JWTDecoded.claims.exp
$NowTimeUTC = Get-Date
$origin = New-Object -Type DateTime -ArgumentList 1970, 1, 1, 0, 0, 0, 0
$JWTIssuedTime = $origin.AddSeconds($JWTI)
$JWTExpireTime = $origin.AddSeconds($JWTE)
#Write-Host $JWTIssuedTime $JWTExpireTime
if ($CQDVer -eq "V2") {
if ($JWTDecoded.claims.aud -eq "https://cqd.lync.com") {
if ($NowTimeUTC.ToUniversalTime() -gt $JWTExpireTime) {
Write-Host "Token Expired"
Connect-CqdOnline
}
}
else {
write-host "Wrong Token, Expecting V2"
Connect-CqdOnline
}
}
elseif ($CQDVer -eq "V3") {
if ($JWTDecoded.claims.aud -eq "https://cqd.teams.microsoft.com") {
if ($NowTimeUTC.ToUniversalTime() -gt $JWTExpireTime) {
Write-Host "Token Expired"
Connect-CqdOnline
}
}
else {
write-host "Wrong Token, Expecting V3"
Connect-CqdOnline
}
}
}
}
###############################
# END AAD AUTH FUNCTIONS #
###############################
#Function to get Array list of Dimensions available in CQD Cube
function Get-CQDDimensions {
$DimensionsCheck = GetParams "Dimensions"
return $DimensionsCheck
}
Export-ModuleMember -Function Get-CQDDimensions
function Get-CQDMeasures {
$MeasuresCheck = GetParams "Measures"
return $MeasuresCheck
}
Export-ModuleMember -Function Get-CQDMeasures
##Generate Dynamic List of CQD Measures and Dimensions
function GetParams ([string]$ParamType) {
CheckToken
$CubeRequest = Invoke-WebRequest -Uri ('{0}CubeStructure' -f $DataServiceBaseUrl) -WebSession $WebSession -Method Get -UserAgent "CQDPowerShell V2.0"
$List = ConvertFrom-Json $CubeRequest
$D = $List.Dimensions
$Meas = $List.Measurements
$Dimensions = @()
$Measures = @()
foreach ($i in $D) {
$Dimensions += $i.Category
$Dimensions += $i.Attributes
}
foreach ($a in $Meas) {
$Measures += $a.Category
$Measures += $a.Attributes
}
if ($ParamType -eq "Dimensions") {
$DimensionName = $Dimensions.DataModelName
$Di = @()
foreach ($O in $DimensionName) {
$O = $O.Replace("[", "")
$O = $O.Replace("]", "")
$Di += $O
}
return $Di
}
elseif ($ParamType -eq "Measures") {
$MeasureName = $Measures.DataModelName
$Mi = @()
foreach ($M in $MeasureName) {
$M = $M.Replace("[", "")
$M = $M.Replace("]", "")
$Mi += $M
}
return $Mi
}
}
#Function for handling start-end date
function ProcessDateRange {
$TS = New-TimeSpan $StartDate $EndDate
if ($TS.Days -lt 0) {
$DateErrorStartEnd = 'Error in Timerange. Confirm StartDate is BEFORE EndDate'
Write-Host $DateErrorStartEnd
throw $DateErrorStartEnd
}
$i = $TS.Days
if
($StartDate -eq $EndDate)
{ $DateList = @($EndDate) }
else {
$DateList = @($EndDate)
do {
$DateList += $EndDate.AddDays(-$i)
$i --
}
while ($i -ne 0)
}
foreach ($D in $DateList) {
$DateF += "[" + $D.ToString('yyyy-MM-dd') + "],"
}
return $DateF
}
#Function to obtain days of week
function GetDaysofWeek {
foreach ($DofWT in $Weekdays) {
$DofW += "[" + $DofWT + "],"
}
return $DofW
}
function BuildWeekFilter {
param(
[Parameter()] [array]$TimeInput
)
# Create list containing "start of weeks'" (Sun) for last 6 month
$endDay = Get-Date
$startDay = (Get-Date).AddMonths(-6)
$cqdLastSixMonthWeeks = @()
for ($i = $startDay; $i -lt $endDay; $i = $i.AddDays(1)) {
if (($i.DayOfWeek).ToString() -eq "Sunday") {
$cqdLastSixMonthWeeks += $i.ToString("yyyy-MM-dd")
}
}
# Initialize variable that will keep final list of "start of weeks'"
$cqdWeeks = @()
# There are two cases:
# 1. Month is provided as an input e.g. "09" for Sep. Must be in this format. length of 2
# 2. Start of week is provided as an input e.g. "2017-09-18". Must be in this format. length of 10
$TimeInput | ForEach-Object {
if ($_.Length -eq 2) {
$tempMonth = $_
$cqdLastSixMonthWeeks | ForEach-Object {
if ($_ -like "*-$($tempMonth)-*") { $cqdWeeks += $_ }
}
}
elseif ($_.Length -eq 10) {
$cqdWeeks += $_
}
}
# Create hash table representing CQD Week filter
$cqdFilterWeek = @{}
$Caption = ""
$Value = ""
$cqdWeeks | ForEach-Object { $Caption += "$($_) | " }
$cqdWeeks | ForEach-Object { $Value += "[$($_)]," }
$cqdFilterWeek.Add("DataModelName", "[AllStreams].[Week]")
$cqdFilterWeek.Add("Caption", $Caption)
$cqdFilterWeek.Add("Value", $Value)
$cqdFilterWeek.Add("Operand", 0)
$cqdFilterWeek.Add("UnionGroup", "")
# Return Json object representing CQD Week filter
return ($cqdFilterWeek | ConvertTo-Json)
}
#Function for creating UA Category Filter
function BuildUACategoryFilter {
param(
[Parameter()] [array]$UACategory
)
# Create hash table representing CQD UA Category filter
$cqdFilterUACategory = @{}
$Caption = ""
$Value = ""
$UACategory | ForEach-Object { $Caption += "$($_) | " }
$Caption | ForEach-Object {
$Length = $Caption.Trim().Length
$Caption = $Caption.Trim().Substring(0, $Length - 1)
$Caption = $Caption.Trim()
}
$UACategory | ForEach-Object { $Value += "[$($_)]," }
$Value | ForEach-Object {
$Length = $Value.Trim().Length
$Value = $Value.Trim().Substring(0, $Length - 1)
$Value = $Value.Trim()
}
$cqdFilterUACategory.Add("DataModelName", "[AllStreams].[Second User Agent Category]")
$cqdFilterUACategory.Add("Caption", $Caption)
$cqdFilterUACategory.Add("Value", $Value)
$cqdFilterUACategory.Add("Operand", 0)
$cqdFilterUACategory.Add("UnionGroup", "")
# Return Json object representing CQD UA Category filter
return ($cqdFilterUACategory | ConvertTo-Json)
}
#Function for creating Media Type Filter
function BuildMediaTypeFilter {
param(
[Parameter()] [array]$MediaType
)
# Create hash table representing CQD Media Type filter
$cqdFilterMediaType = @{}
$Caption = ""
$Value = ""
$MediaType | ForEach-Object { $Caption += "$($_) | " }
$Caption | ForEach-Object {
$Length = $Caption.Trim().Length
$Caption = $Caption.Trim().Substring(0, $Length - 1)
$Caption = $Caption.Trim()
}
$MediaType | ForEach-Object { $Value += "[$($_)]," }
$Value | ForEach-Object {
$Length = $Value.Trim().Length
$Value = $Value.Trim().Substring(0, $Length - 1)
$Value = $Value.Trim()
}
$cqdFilterMediaType.Add("DataModelName", "[AllStreams].[Media Type]")
$cqdFilterMediaType.Add("Caption", $Caption)
$cqdFilterMediaType.Add("Value", $Value)
$cqdFilterMediaType.Add("Operand", 0)
$cqdFilterMediaType.Add("UnionGroup", "")
# Return Json object representing CQD Media Type filter
return ($cqdFilterMediaType | ConvertTo-Json)
}
#Function for Server Pair Filter
function BuildIsServerPairFilter {
param(
[Parameter()] [array]$IsServerPair
)
# Create hash table representing CQD Is Server Pair filter
$cqdFilterIsServerPair = @{}
$Caption = ""
$Value = ""
$IsServerPair | ForEach-Object { $Caption += "$($_) | " }
$Caption | ForEach-Object {
$Length = $Caption.Trim().Length
$Caption = $Caption.Trim().Substring(0, $Length - 1)
$Caption = $Caption.Trim()
}
$IsServerPair | ForEach-Object { $Value += "[$($_)]," }
$Value | ForEach-Object {
$Length = $Value.Trim().Length
$Value = $Value.Trim().Substring(0, $Length - 1)
$Value = $Value.Trim()
}
$cqdFilterIsServerPair.Add("DataModelName", "[AllStreams].[Is Server Pair]")
$cqdFilterIsServerPair.Add("Caption", $Caption)
$cqdFilterIsServerPair.Add("Value", $Value)
$cqdFilterIsServerPair.Add("Operand", 0)
$cqdFilterIsServerPair.Add("UnionGroup", "")
# Return Json object representing CQD Is Server Pair filter
return ($cqdFilterIsServerPair | ConvertTo-Json)
}
#Function for Transport Filter (TCP,UDP)
function BuildTransportFilter {
param(
[Parameter()] [array]$Transport
)
# Create hash table representing CQD transport filter
$cqdFilterTransport = @{}
$Caption = ""
$Value = ""
$Transport | ForEach-Object { $Caption += "$($_) | " }
$Caption | ForEach-Object {
$Length = $Caption.Trim().Length
$Caption = $Caption.Trim().Substring(0, $Length - 1)
$Caption = $Caption.Trim()
}
$Transport | ForEach-Object { $Value += "[$($_)]," }
$Value | ForEach-Object {
$Length = $Value.Trim().Length
$Value = $Value.Trim().Substring(0, $Length - 1)
$Value = $Value.Trim()
}
$cqdFilterTransport.Add("DataModelName", "[AllStreams].[Transport]")
$cqdFilterTransport.Add("Caption", $Caption)
$cqdFilterTransport.Add("Value", $Value)
$cqdFilterTransport.Add("Operand", 0)
$cqdFilterTransport.Add("UnionGroup", "")
# Return Json object representing CQD transport filter
return ($cqdFilterTransport | ConvertTo-Json)
}
#Function for building all Filters
function FilterCreation {
#Build MonthYear Array From Input
foreach ($MonthYearI in $MonthYear) {
$MonthYearParams += "[" + $MonthYearI + "],"
}
$Filters = New-Object system.Data.DataTable "Filters"
$FilterName = New-Object system.Data.DataColumn FilterName, ([string])
$FilterValue = New-Object system.Data.DataColumn FilterValue, ([string])
$FilterCaption = New-Object system.Data.DataColumn FilterCaption, ([string])
$FilterOperand = New-Object system.Data.DataColumn FilterOperand, ([string])
$FilterUnionGroup = New-Object system.Data.DataColumn FilterUnionGroup, ([string])
#Add the Columns
$Filters.columns.Add($FilterName)
$Filters.columns.Add($FilterValue)
$Filters.columns.Add($FilterCaption)
$Filters.columns.Add($FilterOperand)
$Filters.columns.Add($FilterUnionGroup)
if ($Weekdays -ne $null) {
$row = $Filters.NewRow()
$row.FilterName = "AllStreams.Day Of Week"
$row.FilterValue = "$DaysofWeekList"
$row.FilterCaption = "NA"
$row.FilterOperand = "0"
$row.FilterUnionGroup = ""
$Filters.Rows.Add($row)
}
if ($MonthYear -ne $null) {
#Create a row
$row = $Filters.NewRow()
$row.FilterName = "AllStreams.Month Year"
$row.FilterValue = "$MonthYearParams"
$row.FilterCaption = "NA"
$row.FilterOperand = "0"
$row.FilterUnionGroup = ""
$Filters.Rows.Add($row)
}
if ($StartDate -ne $null -and $EndDate -ne $null) {
$EndDateV = ProcessDateRange
#Create a row
$row = $Filters.NewRow()
$row.FilterName = "AllStreams.Date"
$row.FilterValue = "$EndDateV"
$row.FilterCaption = "NA"
$row.FilterOperand = "0"
$row.FilterUnionGroup = ""
$Filters.Rows.Add($row)
}
if ($Week -ne $null) {
$WeekV = (BuildWeekFilter $Week) | ConvertFrom-Json
$row = $Filters.NewRow()
$row.FilterName = "AllStreams.Week"
$row.FilterValue = $WeekV.Value
$row.FilterCaption = "NA"
$row.FilterOperand = $WeekV.Operand
$row.FilterUnionGroup = $WeekV.UnionGroup
$Filters.Rows.Add($row)
}
if ($UACategory -ne $null) {
$UACategoryV = (BuildUACategoryFilter $UACategory) | ConvertFrom-Json
$row = $Filters.NewRow()
$row.FilterName = "AllStreams.Second User Agent Category"
$row.FilterValue = $UACategoryV.Value
$row.FilterCaption = "NA"
$row.FilterOperand = $UACategoryV.Operand
$row.FilterUnionGroup = $UACategoryV.UnionGroup
$Filters.Rows.Add($row)
}
if ($MediaType -ne $null) {
$MediaTypeV = (BuildMediaTypeFilter $MediaType) | ConvertFrom-Json
$row = $Filters.NewRow()
$row.FilterName = "AllStreams.Media Type"
$row.FilterValue = $MediaTypeV.Value
$row.FilterCaption = "NA"
$row.FilterOperand = $MediaTypeV.Operand
$row.FilterUnionGroup = $MediaTypeV.UnionGroup
$Filters.Rows.Add($row)
}
if ($IsServerPair -ne $null) {
$IsServerPairV = (BuildIsServerPairFilter $IsServerPair) | ConvertFrom-Json
$row = $Filters.NewRow()
$row.FilterName = "AllStreams.Is Server Pair"
$row.FilterValue = $IsServerPairV.Value
$row.FilterCaption = "NA"
$row.FilterOperand = $IsServerPairV.Operand
$row.FilterUnionGroup = $IsServerPairV.UnionGroup
$Filters.Rows.Add($row)
}
if ($Transport -ne $null) {
$TransportV = (BuildTransportFilter $Transport) | ConvertFrom-Json
$row = $Filters.NewRow()
$row.FilterName = "AllStreams.Transport"
$row.FilterValue = $TransportV.Value
$row.FilterCaption = "NA"
$row.FilterOperand = $TransportV.Operand
$row.FilterUnionGroup = $TransportV.UnionGroup
$Filters.Rows.Add($row)
}
if ($null -ne $CustomFilter) {
foreach ($F in $CustomFilter) {
$row = $Filters.NewRow()
$row.FilterName = $F.FName
$row.FilterValue = $F.FValue
$row.FilterCaption = ""
$row.FilterOperand = $F.Op
$row.FilterUnionGroup = $F.FUnionGroup
$Filters.Rows.Add($row)
}
}
return $Filters
}
function Get-CQDData {
[CmdletBinding()]
param(
[Parameter(Mandatory = $false, Position = 3)]
[array]$Transport = $null,
[Parameter(Mandatory = $false, Position = 4)]
[string]$OutPutFilePath = $null,
[Parameter(Mandatory = $false, Position = 5)]
[nullable[datetime]]$StartDate = $null,
[Parameter(Mandatory = $false, Position = 6)]
[nullable[datetime]]$EndDate = $null,
[Parameter(Mandatory = $false, Position = 7)]
[array]$MonthYear = $null,
[Parameter(Mandatory = $false, Position = 8)]
[array]$Weekdays = $null,
[Parameter(Mandatory = $True, Position = 9)]
[ValidateSet("CSV", "DataTable")]
[string]$OutPutType,
[Parameter(Mandatory = $false, Position = 10)]
[array]$Week = $null,
[Parameter(Mandatory = $false, Position = 11)]
[array]$UACategory = $null,
[Parameter(Mandatory = $false, Position = 12)]
[array]$MediaType = $null,
[Parameter(Mandatory = $false, Position = 13)]
[ValidateSet("Client : Client", "Client : Server", "Server : Server")]
[array]$IsServerPair = $null,
[Parameter(Mandatory = $false, Position = 14)]
[bool]$ShowQuery = $false,
[Parameter(Mandatory = $false, Position = 15)]
[switch] $OverWriteOutput,
[Parameter(Mandatory = $false, Position = 16)]
[pscustomobject] $CustomFilter,
[Parameter(Mandatory = $false, Position = 17)]
[switch] $LargeQuery,
[Parameter(Mandatory = $false, Position = 18)]
[ValidateSet("V2", "V3")]
[string]$CQDVer = "V3"
)
dynamicparam {
# Set the dynamic parameters' name for Dimensions and Measures
$DimensionParameter = 'Dimensions'
$MeasuresParameter = 'Measures'
# Create the dictionary
$RuntimeParamDictionary = New-Object System.Management.Automation.RuntimeDefinedParameterDictionary
# Create the collection of attributes
$DimensionAttributeCollection = New-Object System.Collections.ObjectModel.Collection[System.Attribute]
$AttributeCollectionMeasures = New-Object System.Collections.ObjectModel.Collection[System.Attribute]
# Create and set the parameters' attributes
$DimensionParameterAttribute = New-Object System.Management.Automation.ParameterAttribute
$DimensionParameterAttribute.Mandatory = $true
$DimensionParameterAttribute.Position = 1
$MeasuresParameterAttribute = New-Object System.Management.Automation.ParameterAttribute
$MeasuresParameterAttribute.Mandatory = $true
$MeasuresParameterAttribute.Position = 2
# Add the attributes to the attributes collection
$DimensionAttributeCollection.Add($DimensionParameterAttribute)
$AttributeCollectionMeasures.Add($MeasuresParameterAttribute)
# Generate and set the ValidateSet
$DimensionarrSet = GetParams "Dimensions"
$MeasuresarrSet = GetParams "Measures"
$DimensionsValidateSetAttribute = New-Object System.Management.Automation.ValidateSetAttribute ($DimensionarrSet)
$MeasuresValidateSetAttribute = New-Object System.Management.Automation.ValidateSetAttribute ($MeasuresarrSet)
# Add the ValidateSet to the attributes collection
$DimensionAttributeCollection.Add($DimensionsValidateSetAttribute)
$AttributeCollectionMeasures.Add($MeasuresValidateSetAttribute)
# Create and return the dynamic parameter
$DimensionsRuntimeParameter = New-Object System.Management.Automation.RuntimeDefinedParameter ($DimensionParameter, [array], $DimensionAttributeCollection)
$MeasuresRuntimeParameter = New-Object System.Management.Automation.RuntimeDefinedParameter ($MeasuresParameter, [array], $AttributeCollectionMeasures)
$RuntimeParamDictionary.Add($DimensionParameter, $DimensionsRuntimeParameter)
$RuntimeParamDictionary.Add($MeasuresParameter, $MeasuresRuntimeParameter)
return $RuntimeParamDictionary
}
begin {
# Bind the parameter to a friendly variable
$Dims = $PsBoundParameters[$DimensionParameter]
$Measures = $PsBoundParameters[$MeasuresParameter]
}
process {
try {
Write-Host "Working...."
#Check for Null CSV Path if CSV Chosen output
if ($OutPutType -eq "CSV" -and $OutPutFilePath -eq "") {
while ($OutPutFilePath -eq "" -or $OutPutFilePath -eq $null) {
Write-Host "You must specify an output path when using CSV output type"
Write-Host "Enter CSV Output Path:" -NoNewline
$OutputFilePath = Read-Host
}
if ($OutputFilePath -eq $null) { Exit-PSSession }
}
$DimFixed = @()
$DimSimple = @()
$MeasureFixed = @()
$MeasureSimple = @()
###Fix Dimension Brackets
foreach ($DimShort in $Dims) {
$Dim1 = $DimShort.Split(".")
$DimSimple += $Dim1[1].ToString()
$Dim1[0] = "[" + $Dim1[0] + "]"
$Dim1[1] = "[" + $Dim1[1] + "]"
$DimFixed += $Dim1[0] + "." + $Dim1[1]
}
foreach ($MeasureShort in $Measures) {
$Measure1 = $MeasureShort.Split(".")
$MeasureSimple += $Measure1[1].ToString()
$Measure1[0] = "[" + $Measure1[0] + "]"
$Measure1[1] = "[" + $Measure1[1] + "]"
$MeasureFixed += $Measure1[0] + "." + $Measure1[1]
}
$Dims = $DimFixed
$Measures = $MeasureFixed
if ($Weekdays -ne $null) {
$DaysofWeekList = GetDaysofWeek
}
else {
$Weekdays = $null
}
$Filters = FilterCreation
##Dimension and Measure Arrays##
$DimensionsArray = $Dims
$MeasurementsArray = $Measures
##Create Results Table##
$DataResults = New-Object system.Data.DataTable "DataResults"
foreach ($DimensionVar in $DimSimple) {
$Column = New-Object system.Data.DataColumn $DimensionVar, ([string])
$DataResults.columns.Add($Column)
}
foreach ($MeasureVar in $MeasureSimple) {
$Column = New-Object system.Data.DataColumn $MeasureVar, ([string])
$DataResults.columns.Add($Column)
}
$FilterRowArray = @()
$DimensionRowArray = @()
$MeasureRowArray = @()
$AllArray = $DimSimple + $MeasureSimple
##Build Query Structure##
#Start/End Query
$StartQuery = "{"
$EndQuery = "}"
#Filter Sections
$StartFilters = @'
"Filters":[
'@
#Dimension Sections
$StartDimensions = @'
"Dimensions":[
'@
#Measure Sections
$StartMeasures = @'
"Measurements":[
'@
###############Loop Arrays of Each Type
foreach ($Filter in $Filters) {
$FLN = $Filter.FilterName
$FCN = $Filter.FilterCaption
$FVE = $Filter.FilterValue
$FOP = $Filter.FilterOperand
$UNGP = $Filter.FilterUnionGroup
$FLNSplit = $FLN.Split(".")
$FLNName = "[" + $FLNSplit[0] + "].[" + $FLNSplit[1] + "]"
$FilterRowArray += @"
{"DataModelName":"$FLNName","Caption":"$FCN","Value":"$FVE","Operand":$FOP,"UnionGroup":"$UNGP"},
"@
}
$DimCount = $DimensionsArray.Count - 1
foreach ($DimensionLoop in $DimensionsArray) {
$DimensionRowArray += @"
{"DataModelName":"$DimensionLoop"},
"@
}
$MeaCount = $MeasurementsArray.Count - 1
foreach ($MeasureLoop in $MeasurementsArray) {
$MeasureRowArray += @"
{"DataModelName":"$MeasureLoop"},
"@
}
########Build Dynamic Query
if ($LargeQuery) {
$Query = @"
{
$StartFilters
$FilterRowArray
]
,
$StartDimensions
$DimensionRowArray
]
,
$StartMeasures
$MeasureRowArray
]
,
LimitResultRowsCount:200000
}
"@
}
else {
$Query = @"
{
$StartFilters
$FilterRowArray
]
,
$StartDimensions
$DimensionRowArray
]
,
$StartMeasures
$MeasureRowArray
],
LimitResultRowsCount:200000
}
"@
}
#Check to see if ShowQuery is true. Used to show JSON query for debugging queries.
if ($ShowQuery -eq $true) {
Write-Host "JSON Query:"
Write-Host $Query
}
CheckToken
$verb = "POST"
$content = $Query
$headers = New-Object "System.Collections.Generic.Dictionary[[String],[String]]"
$IRM = Invoke-RestMethod -Uri ('{0}RunQuery' -f $DataServiceBaseUrl) -WebSession $WebSession -Method Post -Body $Query -ContentType 'application/json' -UserAgent "CQDPowerShell V2.0" -Headers $headers
$IRM2 = ConvertTo-Json -InputObject $IRM
$JsonGarb = ConvertFrom-Json -InputObject $IRM2
$QueryExecutionTime = $JsonGarb.ExecutionTime
$ErrorType = $JsonGarb.ErrorType
$ResultList = $JsonGarb.DataResult
if ($ErrorType -ne 0) {
Write-Host "Error Querying CQD with Error " $ErrorType
if ($ErrorType -eq 6) { Write-Host "Invalid Query. Check the query and try again." }
if ($ErrorType -eq 5) { Write-Host "Query scope too large. Reduce Dimensions, Measures and Timespan" }
if ($ErrorType -eq 3) { Write-Host "Cube currently unavailable. Try again later." }
}
foreach ($ResultItem in $ResultList) {
if (!$ResultItem) {
#if(1 -eq 2)
Write-Host "Warning: Result is Null:" $ResultItem
}
else {
$ItemCount = $ResultItem.Count