PowerBIPS.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
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
<#
 
Checkout more products and samples at:
    - http://devscope.net/
    - https://github.com/DevScope
 
PowerBI API documentation:
 
    - https://msdn.microsoft.com/library/dn877544
 
Copyright (c) 2015 DevScope
 
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
 
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
 
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
 
#>


#region Constants/Variables

$pbiAuthorityUrl = "https://login.windows.net/common/oauth2/authorize"
$pbiResourceUrl = "https://analysis.windows.net/powerbi/api"
$pbiDefaultAuthRedirectUri = "https://login.live.com/oauth20_desktop.srf"
$pbiDefaultClientId = "d57ac8af-1019-431d-8fed-5fd8db180388"

$script:pbiGroupId = $null

#endregion

Function Get-PBIAuthToken
{
    <#
            .SYNOPSIS
            Gets the authentication token required to comunicate with the PowerBI API's
 
 
            .DESCRIPTION
            To authenticate with PowerBI uses OAuth 2.0 with the Azure AD Authentication Library (ADAL)
 
            If a credential is not supplied a popup will appear for the user to authenticate.
 
            It will automatically download and install the required nuget: "Microsoft.IdentityModel.Clients.ActiveDirectory".
 
            .PARAMETER ClientId
            The Client Id of the Azure AD application
 
            .PARAMETER Credential
            Specifies a PSCredential object or a string username used to authenticate to PowerBI. If only a username is specified
            this will prompt for the password. Note that this will not work with federated users.
 
            .PARAMETER RedirectUri
            The redirect URI associated with the native client application
 
            .PARAMETER ForceAskCredentials
            Forces the authentication popup to always ask for the username and password
 
            .EXAMPLE
            Get-PBIAuthToken -clientId "C0E8435C-614D-49BF-A758-3EF858F8901B"
            Returns the access token for the PowerBI REST API using the client ID. You'll be presented with a pop-up window for
            user authentication.
            .EXAMPLE
            $Credential = Get-Credential
            Get-PBIAuthToken -ClientId "C0E8435C-614D-49BF-A758-3EF858F8901B" -Credential $Credential
            Returns the access token for the PowerBI REST API using the client ID and a PSCredential object.
    #>

    
    [CmdletBinding(DefaultParameterSetName = 'default')]
    [OutputType([string])]
    param
    (
        [Parameter(ParameterSetName = 'default')]
        [Parameter(ParameterSetName = 'credential')]
        [string]
        $ClientId = $pbiDefaultClientId,

        [Parameter(Mandatory = $true, ParameterSetName = 'credential')]
        [System.Management.Automation.CredentialAttribute()]
        $Credential,

        [Parameter(ParameterSetName = 'default')]
        [string]
        $RedirectUri = $PBIDefaultAuthRedirectUri,

        [Parameter(ParameterSetName = 'default')]
        [switch]
        $ForceAskCredentials = $false
    )

   

    if ($Script:AuthContext -eq $null)
    {
        Write-Verbose -Message 'Creating new AuthenticationContext object'
        $script:AuthContext = New-Object -TypeName Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContext -ArgumentList ($PBIAuthorityUrl)
    }

    Write-Verbose -Message 'Getting the Authentication Token'
    if ($PSCmdlet.ParameterSetName -eq 'credential')
    {
        Write-Verbose -Message 'Using username+password authentication flow'
        $UserCredential = New-Object -TypeName Microsoft.IdentityModel.Clients.ActiveDirectory.UserCredential -ArgumentList ($Credential.UserName, $Credential.Password)
        $AuthResult = $Script:AuthContext.AcquireToken($PbiResourceUrl,$ClientId, $UserCredential)
    }
    else
    {
        Write-Verbose -Message 'Using default authentication flow'
        if ($ForceAskCredentials)
        {
            $PromptBehavior = [Microsoft.IdentityModel.Clients.ActiveDirectory.PromptBehavior]::Always
        }
        else
        {
            $PromptBehavior = [Microsoft.IdentityModel.Clients.ActiveDirectory.PromptBehavior]::Auto
        }
        $authResult = $script:authContext.AcquireToken($PbiResourceUrl,$ClientId, [Uri]$RedirectUri, $PromptBehavior)
    }

    Write-Verbose -Message "Authenticated as $($AuthResult.UserInfo.DisplayableId)"
    $AuthResult.AccessToken
}

Function Set-PBIGroup{
<#
.SYNOPSIS
   Set's the scope to the group specified, after execution all the following PowerBIPS cmdlets will execute over the setted group.
 
.PARAMETER AuthToken
    The authorization token required to communicate with the PowerBI APIs
    Use 'Get-PBIAuthToken' to get the authorization token string
 
.PARAMETER Id
    The id of the group
     
.PARAMETER Name
    The name of the group
 
.PARAMETER Clear
    If $true then will clear the group and all the requests will be made to the default user workspace
 
#>

    [CmdletBinding()]        
    param(                                    
        [Parameter(Mandatory=$false)] [string] $authToken,
        [Parameter(Mandatory=$false)] [string] $id,
        [Parameter(Mandatory=$false)] [string] $name,
        [Parameter(Mandatory=$false)] [switch] $clear = $false            
    )
        
    if ($clear)
    {
        $script:pbiGroupId = $null
    }
    else
    {
        $script:pbiGroupId = Resolve-GroupId $authToken $id $name
    }
}

Function Get-PBIDashboard{
<#
.SYNOPSIS
    Gets all the PowerBI existing dashboards and returns as an array of custom objects.
         
.EXAMPLE
             
        Get-PBIDashboard -authToken $authToken
 
#>

    [CmdletBinding()]        
    param(                                    
        [Parameter(Mandatory=$false)] [string] $authToken,
        [Parameter(Mandatory=$false)] [string] $name,
        [Parameter(Mandatory=$false)] [string] $id        
    )
    
    $authToken = Resolve-PowerBIAuthToken $authToken

    $headers = Get-PowerBIRequestHeader $authToken

    Write-Verbose "Getting Dashboards"
    
    $result = Invoke-RestMethod -Uri (Get-PowerBIRequestUrl -scope "dashboards" -beta) -Headers $headers -Method Get 
    
    $dashboards = $result.value
    
    Write-Verbose "Found $($dashboards.count) groups."            
    
    if (-not [string]::IsNullOrEmpty($name))
    {
        Write-Verbose "Searching for the dashboard '$name'"        
        
        $dashboards = @($dashboards |? name -eq $name)
        
        if ($dashboards.Count -ne 0)
        {
            Write-Verbose "Found dashboard with name: '$name'"                
        }
        else
        {
            throw "Cannot find dashboard with name: '$name'"            
        }                
    }    

    Write-Output $dashboards
}

Function Get-PBIDashboardTile{
<#
.SYNOPSIS
    Gets all the PowerBI existing dashboards and returns as an array of custom objects.
         
.EXAMPLE
             
        Get-PBIDashboardTile -authToken $authToken -dashboardId "XXXX-XXXX-XXXX"
 
#>

    [CmdletBinding()]        
    param(                                    
        [Parameter(Mandatory=$false)] [string] $authToken,
        [Parameter(Mandatory=$false)] [string] $dashboardId,    
        [Parameter(Mandatory=$false)] [string] $tileId
    )
    
    $authToken = Resolve-PowerBIAuthToken $authToken

    $headers = Get-PowerBIRequestHeader $authToken

    Write-Verbose "Getting Dashboard '$dashboardId' tiles"
    
    $scope = "dashboards/$dashboardId/tiles"

    if (-not [string]::IsNullOrEmpty($tileId))
    {
        $scope += "/$tileId"
    }

    $result = Invoke-RestMethod -Uri (Get-PowerBIRequestUrl -scope $scope -beta) -Headers $headers -Method Get 
    
    if ($result.value)
    {
        $tiles = $result.value
    }
    else
    {
        $tiles = @($result)
    }    
    
    Write-Verbose "Found $($tiles.count) tiles."                

    Write-Output $tiles
}

Function Get-PBIGroup{
<#
.SYNOPSIS
    Gets all the PowerBI existing groups and returns as an array of custom objects.
         
.EXAMPLE
             
        Get-PBIGroup -authToken $authToken
 
#>

    [CmdletBinding()]        
    param(                                    
        [Parameter(Mandatory=$false)] [string] $authToken,
        [Parameter(Mandatory=$false)] [string] $name,
        [Parameter(Mandatory=$false)] [string] $id        
    )

    $authToken = Resolve-PowerBIAuthToken $authToken

    $headers = Get-PowerBIRequestHeader $authToken

    Write-Verbose "Getting Groups"
    
    $result = Invoke-RestMethod -Uri (Get-PowerBIRequestUrl -scope "groups" -ignoreGroup) -Headers $headers -Method Get 
    
    $groups = $result.value
    
    Write-Verbose "Found $($groups.count) groups."            
    
    if (-not [string]::IsNullOrEmpty($name))
    {
        Write-Verbose "Searching for the group '$name'"        
        
        $groups = @($groups |? name -eq $name)
        
        if ($groups.Count -ne 0)
        {
            Write-Verbose "Found group with name: '$name'"                
        }
        else
        {
            throw "Cannot find group with name: '$name'"            
        }                
    }    

    Write-Output $groups
}

Function Get-PBIDataSet{
<#
.SYNOPSIS
    Gets all the PowerBI existing datasets and returns as an array of custom objects.
    Or
    Check if a dataset exists with the specified name and if exists returns it's metadata
 
.DESCRIPTION
    Gets all the PowerBI existing datasets and returns as an array of custom objects.
    Or
    Check if a dataset exists with the specified name and if exists returns it's metadata
 
.PARAMETER AuthToken
    The authorization token required to communicate with the PowerBI APIs
    Use 'Get-PBIAuthToken' to get the authorization token string
 
.PARAMETER Name
    The dataset name
     
.PARAMETER Id
    The dataset id
     
.PARAMETER IncludeDefinition
    If specified will include the dataset definition properties
     
.PARAMETER IncludeTables
    If specified will include the dataset tables
     
.EXAMPLE
             
        Get-PBIDataSet -authToken $authToken
        Get-PBIDataSet -authToken $authToken -name "DataSetName"
        Get-PBIDataSet -authToken $authToken -name "DataSetName" -includeDefinition -includeTables
 
#>

    [CmdletBinding()]        
    param(                                    
        [Parameter(Mandatory=$false)] [string] $authToken,
        [Parameter(Mandatory=$false)] [string] $name,
        [Parameter(Mandatory=$false)] [string] $id,
        [Parameter(Mandatory=$false)] [switch] $includeDefinition,
        [Parameter(Mandatory=$false)] [switch] $includeTables        
    )

    $authToken = Resolve-PowerBIAuthToken $authToken
    $headers = Get-PowerBIRequestHeader $authToken
        
    $url = Get-PowerBIRequestUrl -scope "datasets"
    
    if ([string]::IsNullOrEmpty($id))
    {
        Write-Verbose "Getting DataSets"                
        
        $result = Invoke-RestMethod -Uri $url -Headers $headers -Method Get 
        
        $dataSets = $result.value
        
        Write-Verbose "Found $($dataSets.count) datasets."            
        
        if (-not [string]::IsNullOrEmpty($name))
        {
            Write-Verbose "Searching for the dataset '$name'"        
            
            $dataSets = @($dataSets |? name -eq $name | Select -First 1)
            
            if ($dataSets.Count -ne 0)
            {
                Write-Verbose "Found dataset with name: '$name'"                
            }
            else
            {
                Write-Verbose "Cannot find dataset with name: '$name'"
                return
            }                
        }
        
        # if IncludeDefinition is true then go get the definition of the dataset and change the PSObject
        
        if ($includeDefinition)
        {                
            $dataSets |% {
                $dataSet = $_
                
                $dataSetDefinition = Get-PBIDataSet -authToken $authToken -id $_.Id -ErrorAction Continue
                
                $dataSetDefinition | Get-Member -MemberType NoteProperty |%{
                    
                    if (-not $dataSet.$($_.Name))
                    {
                        $dataSet | Add-Member -MemberType NoteProperty -Name $_.Name -Value $dataSetDefinition.$($_.Name)
                    }
                }                                
            }
        }
    }
    else
    {
        Write-Verbose "Getting DataSet Definition"
        
        $result = Invoke-RestMethod -Uri "$url/$id" -Headers $headers -Method Get 
        
        $result | Add-Member -MemberType NoteProperty -Name "id" -Value $id
        
        $dataSets = @($result)        
    }
    
    # if IncludeTables is true then call the GetTables operation
    
    if ($includeTables)
    {                
        $dataSets |% {
            $dataSet = $_                        
            
            $tables = Get-PBIDataSetTables -authToken $authToken -id $_.Id -url $url
                    
            $dataSet | Add-Member -MemberType NoteProperty -Name "tables" -Value $tables            
        }
    }
    
    Write-Output $dataSets
}

Function Test-PBIDataSet{
<#
.SYNOPSIS
    Check if a dataset exists by name
 
.DESCRIPTION
    Check if a dataset exists with the specified name
 
.PARAMETER AuthToken
    The authorization token required to communicate with the PowerBI APIs
    Use 'Get-PBIAuthToken' to get the authorization token string
 
.PARAMETER Name
    The dataset name
     
.EXAMPLE
                                 
        Test-PBIDataSet -authToken $authToken -name "DataSetName"
        Returns $true if the dataset exists
 
#>

    [CmdletBinding()]    
    [OutputType([bool])]
    param(                                    
        [Parameter(Mandatory=$false)] [string] $authToken,
        [Parameter(Mandatory=$true)] $name
    )
            
    $dataSet = Get-PBIDataSet -authToken $authToken -name $name
    
    if ($dataSet)
    {                
        Write-Output $true
    }
    else
    {                
        Write-Output $false
    }
}

Function New-PBIDataSet{
<#
.SYNOPSIS
    Create a new DataSet
 
.DESCRIPTION
    Create a new DataSet in PowerBI
 
.PARAMETER AuthToken
    The authorization token required to comunicate with the PowerBI APIs
    Use 'Get-PBIAuthToken' to get the authorization token string
 
.PARAMETER DataSet
    The dataset object, this object must be one of two types: hashtable or System.Data.DataSet
     
    If a hashtable is supplied it must have the following structure:
         
        $dataSet = @{
            name = "DataSetName"
            ; tables = @(
                @{
                    name = "TableName"
                    ; columns = @(
                        @{ name = "Col1"; dataType = "Int64" }
                        , @{ name = "Col2"; dataType = "string" }
                        )
                })
        }
         
.PARAMETER DefaultRetentionPolicy
    The retention policy to be applied by PowerBI
     
    Example: "basicFIFO"
    http://blogs.msdn.com/b/powerbidev/archive/2015/03/23/automatic-retention-policy-for-real-time-data.aspx
 
.EXAMPLE
                                 
        New-PBIDataSet -authToken $authToken -dataSet $dataSet
        A new dataset will be created and in case of success return the internal dataset id
 
#>

    [CmdletBinding()]    
    param(                                    
        [Parameter(Mandatory=$true)] [string] $authToken,
        [Parameter(Mandatory=$true, HelpMessage = "Must be of type [hashtable] or [dataset]")] $dataSet,
        [Parameter(Mandatory=$false)] [string]$defaultRetentionPolicy,
        [Parameter(Mandatory=$false)] [hashtable]$types
    )
        
    $authToken = Resolve-PowerBIAuthToken $authToken

    $headers = Get-PowerBIRequestHeader $authToken
    
    if ($dataSet -is [hashtable])
    {
        Assert-DataSetObjectSchema $dataSet                
    }
    elseif ($dataSet -is [System.Data.DataSet])
    {
        $dataSet = ConvertTo-PBIDataSet $dataSet
    }
    else
    {
        throw "Invalid 'dataSet' type, must be of type [hashtable] or [dataset]"
    }
    
    $jsonBody = ConvertTo-PBIJson -obj $dataSet -types $types
    
    Write-Verbose "Creating new dataset"    
    
    $url = Get-PowerBIRequestUrl -scope "datasets"
    
    if (-not [string]::IsNullOrEmpty($defaultRetentionPolicy))
    {        
        $url = $url + "?defaultRetentionPolicy=$defaultRetentionPolicy"
    }
    
    $result = Invoke-RestMethod -Uri $url -Headers $headers -Method Post -Body $jsonBody                      
    
    Write-Verbose "DataSet created with id: '$($result.id)"
    
    Write-Output $result
}

Function Update-PBITableSchema{
<#
.SYNOPSIS
    Updates a PowerBI Dataset Table Schema.
    Note: This operation will delete all the table rows
 
.DESCRIPTION
    Updates a PowerBI Dataset Table Schema
 
.PARAMETER AuthToken
    The authorization token required to comunicate with the PowerBI APIs
    Use 'Get-PBIAuthToken' to get the authorization token string
 
.PARAMETER Table
    The table object, this object must be one of two types: hashtable or System.Data.DataTable
     
    If a hashtable is supplied it must have the following structure:
         
        $table = @{
                    name = "TableName"
                    ; columns = @(
                        @{ name = "Col1"; dataType = "Int64" }
                        , @{ name = "Col2"; dataType = "string" }
                        )
                }
 
.EXAMPLE
                                 
        Update-PBITableSchema -authToken $authToken -dataSetId <dataSetId> -table <tableSchema>
 
#>

    [CmdletBinding()]    
    param(                                    
        [Parameter(Mandatory=$false)] [string] $authToken,
        [Parameter(Mandatory=$true)] [string] $dataSetId,                
        [Parameter(Mandatory=$true, HelpMessage = "Must be of type [hashtable] or [datatable]")] $table,
        [Parameter(Mandatory=$false)] [hashtable] $types
    )
                        
    $authToken = Resolve-PowerBIAuthToken $authToken

    $headers = Get-PowerBIRequestHeader $authToken
    
    if ($table -is [hashtable])
    {
        Assert-DataSetTableObjectSchema $table            
    }
    elseif ($table -is [System.Data.DataTable])
    {                
        $table = ConvertTo-PBITableFromDataTable $table                    
    }
    else
    {
        throw "Invalid 'table' type, must be of type [hashtable] or [dataset]"
    }
    
    $jsonBody = ConvertTo-PBIJson -obj $table -types $types
        
    Write-Verbose "Updating Table Schema of '$($table.Name)' on DataSet '$dataSetId'"    
    
    $url = Get-PowerBIRequestUrl -scope "datasets/$dataSetId/tables/$($table.Name)"
    
    $result = Invoke-RestMethod -Uri $url -Headers $headers -Method PUT -Body $jsonBody                      
    
    Write-Verbose "Table schema updated"
        
}

Function Add-PBITableRows{      
<#
.SYNOPSIS
    Add's a collection of rows into a powerbi dataset table in batches
 
.DESCRIPTION
    Add's a collection of rows into a powerbi dataset table in batches
 
.PARAMETER AuthToken
    The authorization token required to comunicate with the PowerBI APIs
    Use 'Get-PBIAuthToken' to get the authorization token string
 
.PARAMETER DataSetId
    The id of the dataset in PowerBI
 
.PARAMETER TableName
    The name of the table of the dataset
 
.PARAMETER Rows
    The collection of rows to insert to the table.
    This parameter can have it's value from the pipeline
 
.PARAMETER BatchSize
    The size of the batch that is sent to PowerBI as HttpPost.
     
    If for example the batch size is 100 and a collection of
    1000 rows are being pushed then this cmdlet will make 10
    HttpPosts
 
.EXAMPLE
         
        Add-PBITableRows -authToken $auth -dataSetId $dataSetId -tableName "Product" -rows $data -batchSize 10
         
.EXAMPLE
         
        1..53 |% { @{id = $_; name = "Product $_"}} | Add-PBITableRows -authToken $auth -dataSetId $dataSetId -tableName "Product" -batchSize 10
        53 records are uploaded to PowerBI "Product" table in batches of 10 rows.
 
#>

    [CmdletBinding()]
    [CmdletBinding(DefaultParameterSetName = "dataSetId")]    
    param(                                            
        [Parameter(Mandatory=$false)] [string] $authToken,
        [Parameter(Mandatory=$true, ParameterSetName = "dataSetId")] [string] $dataSetId,
        [Parameter(Mandatory=$true, ParameterSetName = "dataSetName")] [string] $dataSetName,
        [Parameter(Mandatory=$true)] [string] $tableName,
        [Parameter(Mandatory=$true, ValueFromPipeline = $true)] $rows,
        [Parameter(Mandatory=$false)] [int] $batchSize = 1000        
    )
    
    begin{
        
        $authToken = Resolve-PowerBIAuthToken $authToken

        $headers = Get-PowerBIRequestHeader $authToken                    
    
        $rowsBatch = @()    
        
        if ($PsCmdlet.ParameterSetName -eq "dataSetName")
        {
            $dataSet = Get-PBIDataSet -authToken $authToken -name $dataSetName
            
            if (-not $dataSet)
            {
                throw "Cannot find a DataSet named '$dataSetName'"
            }
            
            $dataSetId = $dataSet.Id
        }
        
        $url = Get-PowerBIRequestUrl -scope "datasets/$dataSetId/tables/$tableName/rows"            
    }
    process{
        
        # Build the batch of rows
                
        $rowsBatch += $rows        
        
        # When the batch is complete send to PBI
        
        if ($batchSize -ne -1 -and $rowsBatch.Count -ge $batchSize)
        {
            Add-PBITableRowsInternal -url $url -headers $headers -rows $rowsBatch
            $rowsBatch = @()
        }
    }
    end{
    
        # If its only one batch upload or is any batch left send to PBI
        
        if ($batchSize -eq -1 -or $rowsBatch.Count -gt 0)
        {
            Add-PBITableRowsInternal -url $url -headers $headers -rows $rowsBatch 
        }        
    }                    
}

Function Add-PBITableRowsInternal{          
    param(                                    
        [Parameter(Mandatory=$true)] [string] $url,
        [Parameter(Mandatory=$true)] [hashtable] $headers,
        [Parameter(Mandatory=$true)] [array] $rows        
    )
    
    $sampleRow = $rows[0]
    
    if ($sampleRow -is [System.Data.DataRow])
    {
        $table = $rows[0].Table
        
        # Convert all the rows from DataRow into a Hashtable with the columns as keys
        
        $rows = $rows |% {
            $row = $_
            
            $hash = @{}
            
            $table.Columns |% {
                $column = $_
                
                $hash.Add($column.ColumnName, $row[$column])
            }                        
            
            $hash
        }        
    }
            
    $bodyObj = @{
            rows = $rows
        } | ConvertTo-Json -Depth 2    
                
    Write-Verbose "Adding a batch of '$($rows.Count)' rows into '$tableName' table of dataset '$dataSetId'"
    
    if ($bodyObj -match """value"":.+\/Date\(")
    {
        Write-Warning "There's an issue with [datetime] and ConvertTo-Json... As an workaround please use -Types parameter to force the column type as [datetime] for example: -Types @{""Table.Date""=""datetime""} and set the row values as string like 'colValue.ToString(""yyyy-MM-dd"")'"
    }
    
    $result = Invoke-RestMethod -Uri $url -Headers $headers -Method Post -Body $bodyObj
}

Function Clear-PBITableRows{      
<#
.SYNOPSIS
    Delete all the rows of a PowerBI dataset table
 
.DESCRIPTION
    Delete all the rows of a PowerBI dataset table
 
.PARAMETER AuthToken
    The authorization token required to comunicate with the PowerBI APIs
    Use 'Get-PBIAuthToken' to get the authorization token string
 
.PARAMETER DataSetId
    The id of the dataset in PowerBI
 
.PARAMETER TableName
    The name of the table of the dataset
 
.EXAMPLE
        Clear-PBITableRows -authToken "authToken" -DataSetId "DataSetId" -TableName "Table"
 
#>

    [CmdletBinding()]
    [CmdletBinding(DefaultParameterSetName = "dataSetId")]    
    param(                                    
        [Parameter(Mandatory=$false)] [string] $authToken,
        [Parameter(Mandatory=$true, ParameterSetName = "dataSetId")] [string] $dataSetId,
        [Parameter(Mandatory=$true, ParameterSetName = "dataSetName")] [string] $dataSetName,
        [Parameter(Mandatory=$true)] [string] $tableName        
    )
    
    $authToken = Resolve-PowerBIAuthToken $authToken

    $headers = Get-PowerBIRequestHeader $authToken
    
    if ($PsCmdlet.ParameterSetName -eq "dataSetName")
    {
        $dataSet = Get-PBIDataSet -authToken $authToken -name $dataSetName
        
        if (-not $dataSet)
        {
            throw "Cannot find a DataSet named '$dataSetName'"
        }
        
        $dataSetId = $dataSet.Id
    }
    
    $url = Get-PowerBIRequestUrl -scope "datasets/$dataSetId/tables/$tableName/rows"
            
    Write-Verbose "Deleting all the rows of '$tableName' table of dataset '$dataSetId'"
    
    $result = Invoke-RestMethod -Uri $url -Headers $headers -Method Delete
    
}

Function Out-PowerBI
{
    <#
            .SYNOPSIS
            A one line cmdlet that you can use to send data into PowerBI
 
            .DESCRIPTION
 
 
            .PARAMETER Data
            The data that will be sent to PowerBI
 
            .PARAMETER ClientId
            The Client Id of the Azure AD application
 
            .PARAMETER AuthToken
            The AccessToken - Optional
 
            .PARAMETER Credential
            specifies a PSCredential object used to authenticate to the PowerBI service. This is used to automate the
            sign in process so you aren't prompted to enter a username and password in the GUI.
 
            .PARAMETER DataSetName
            The name of the dataset - Optional, by default will always create a new dataset with a timestamp
 
            .PARAMETER TableName
            The name of the table in the DataSet - Optional, by default will be named "Table"
 
            .PARAMETER BatchSize
            The size of the batch that is sent to PowerBI as HttpPost.
 
            If for example the batch size is 100 and a collection of
            1000 rows are being pushed then this cmdlet will make 10
            HttpPosts
 
            .PARAMETER MultipleTables
            A indication that the hashtable passed is a multitable
 
            .EXAMPLE
            Get-Process | Out-PowerBI -clientId "7a7be4f7-c64d-41da-94db-7fb8200f029c"
 
            1..53 |% {
            @{
                Id = $_
                ; Name = "Record $_"
                ; Date = [datetime]::Now
                ; Value = (Get-Random -Minimum 10 -Maximum 1000)
            }
            } | Out-PowerBI -clientId "7a7be4f7-c64d-41da-94db-7fb8200f029c" -verbose
 
    #>

    [CmdletBinding(DefaultParameterSetName = "authToken")]
    param
    (
        [Parameter(Mandatory = $true, ValueFromPipeline = $true)]
        $Data,

        [string]
        $ClientId = $pbiDefaultClientId,

        [Parameter(ParameterSetName = "authToken")]
        [string]
        $AuthToken,

        [Parameter(Mandatory = $true, ParameterSetName = "credential")]
        [System.Management.Automation.CredentialAttribute()]
        $Credential,

        [string]
        $DataSetName = ("PowerBIPS_{0:yyyyMMdd_HHmmss}"    -f (Get-Date)),

        [string]
        $TableName    = "Table",
        
        [int]
        $BatchSize = 1000,

        # Need this because $data could be an hashtable (multiple tables) and the rows also can be hashtables...
        [switch]
        $MultipleTables,

        [switch]
        $ForceAskCredentials,

        [switch]
        $ForceTableSchemaUpdate,

        [hashtable]
        $Types
    )

    begin
    {
        $dataToProcess = @()
    }
    process
    {
        $dataToProcess += $Data
    }
    end
    {
        if ($dataToProcess.Count -eq 0)
        {
            Write-Verbose "There is no data to process"
            return
        }

        if ($PsCmdlet.ParameterSetName -eq "credential")
        {
            $AuthToken = Get-PBIAuthToken -ClientId $ClientId -Credential $Credential
        }
        else
        {
            if ([string]::IsNullOrEmpty($AuthToken))
            {
                $AuthToken = Get-PBIAuthToken -ClientId $ClientId -forceAskCredentials:$ForceAskCredentials
            }
        }

        # Prepare the Data to be processed
        if ($dataToProcess.Count -eq 1)
        {
            $dataToProcessSample = $dataToProcess[0]

            # If is a DataSet then transform to a hashtable with DataTables in it
            if ($dataToProcessSample -is [System.Data.DataSet])
            {
                $dataToProcess = @{}

                $dataToProcessSample.Tables | Foreach-Object {
                    $dataToProcess.Add($_.TableName, $_)
                }
            }
            elseif ($MultipleTables -and ($dataToProcessSample -is [hashtable]))
            {
                $dataToProcess = $dataToProcess[0]
            }
            else
            {
                $dataToProcess = @{$TableName = $dataToProcess}
                #throw "When -multipleTables is specified you must pass into -data an hashtable with a key for each table"
            }
        }
        else
        {
            $dataToProcess = @{$TableName = $dataToProcess}
        }

        # Remove empty tables
        $tablesToRemove = $dataToProcess.GetEnumerator() | Where-Object {-not $_.Value } | Select-Object -ExpandProperty Key

        $tablesToRemove | Foreach-Object {
            $dataToProcess.Remove($_)
        }

        # Create the DataSet in PowerBI (if not exists)
        $pbiDataSet = Get-PBIDataSet -authToken $AuthToken -name $DataSetName

        if ($pbiDataSet -eq $null -or $ForceTableSchemaUpdate)
        {
            # Create the DataSet schema object
            $dataSet = @{
                name = $DataSetName
                tables = @()
            }

            # Process each table schema individually
            foreach ($h in ($dataToProcess.GetEnumerator() | Sort-Object -Property Name)) {

                $dataSet.tables += ConvertTo-PBITable -obj $h.Value -name $h.Name
            }

            if ($pbiDataSet -eq $null)
            {
                $pbiDataSet = New-PBIDataSet -authToken $AuthToken -dataSet $dataSet -types $Types
            }
            else
            {
                # Updates the schema of all the tables
                $dataSet.tables | Foreach-Object {
                    Update-PBITableSchema -authToken $AuthToken -dataSetId $pbiDataSet.id -table $_ -types $Types
                }
            }
        }

        # Upload rows for each table
        foreach ($h in ($dataToProcess.GetEnumerator() | Sort-Object -Property Name))
        {

            $TableName = $h.Name
            $tableData = ConvertTo-PBITableData $h.Value
            $tableData | Add-PBITableRows -authToken $AuthToken -dataSetId $pbiDataSet.Id -tableName $TableName -batchSize $BatchSize
        }
    }
}

Function Get-PBIImports{
<#
.SYNOPSIS
    Gets all the PowerBI imports made by the user and returns as an array of custom objects.
         
.EXAMPLE
             
        Get-PBIImports -authToken $authToken
 
#>

    [CmdletBinding()]        
    param(                                    
        [Parameter(Mandatory=$false)] [string] $authToken,
        [Parameter(Mandatory=$false)] [string] $importId            
    )
    
    $authToken = Resolve-PowerBIAuthToken $authToken

    $headers = Get-PowerBIRequestHeader $authToken

    Write-Verbose "Getting Imports"
    
    $scope = "imports"
    
    if (-not [string]::IsNullOrEmpty($importId))
    {
        $scope = "imports/$importId"
    }
    
    $url = Get-PowerBIRequestUrl -scope $scope -beta
    
    $result = Invoke-RestMethod -Uri $url -Headers $headers -Method Get     
    
    if ($result -and ($result.value))
    {                
        Write-Output $result.value        
    }
    else
    {
        Write-Output $result
    }
}


Function Import-PBIFile{
    [CmdletBinding()]        
    param(        
        [Parameter(Mandatory=$false)] [string] $authToken,
        [Parameter(Mandatory=$false)] [string] $dataSetName,
        [Parameter(Mandatory=$false)]
        [ValidateSet("Abort","Overwrite","Ignore")]
        [string]$nameConflict = "Ignore",
        [Parameter(Mandatory=$true)] [string]$filePath        
    )
    
    $authToken = Resolve-PowerBIAuthToken $authToken

    $headers = Get-PowerBIRequestHeader $authToken
    
    $fileName = [IO.Path]::GetFileName($filePath)
    
    if ([string]::IsNullOrEmpty($dataSetName))
    {
        $dataSetName = $fileName
    }
            
    $url = Get-PowerBIRequestUrl -scope "imports?datasetDisplayName=$dataSetName&nameConflict=$nameConflict" -beta
    
    $boundary = [System.Guid]::NewGuid().ToString("N")   
        
    $fileBin = [IO.File]::ReadAllBytes($filePath)
    
    $computer= $env:COMPUTERNAME    
    
    $enc = [System.Text.Encoding]::GetEncoding("iso-8859-1")
    
    $fileEnc = $enc.GetString($fileBin)    
    
    $LF = [System.Environment]::NewLine
    
    $bodyLines = (
        "--$boundary",
        "Content-Disposition: form-data; name=`"file0`"; filename=`"$fileName`"",
        "Content-Type: application/x-zip-compressed$LF",        
        $fileEnc,
        "--$boundary--$LF"
        ) -join $LF
        
    $result = Invoke-RestMethod -Uri $url -Headers $headers -Method Post -ContentType "multipart/form-data; boundary=--$boundary" -Body $bodyLines
    
    Write-Output $result
}

#Function Get-PBIModels{
# [CmdletBinding()]
# param(
# [Parameter(Mandatory=$true)] [string] $authToken
# )
#
# $headers = (Get-PowerBIRequestHeader $authToken)
#
# Write-Verbose "Getting Models"
#
# #$url = Get-PowerBIRequestUrl -scope "/powerbi/metadata/models" -authToken $authToken
#
# $result = Invoke-RestMethod -Uri "https://wabi-us-north-central-redirect.analysis.windows.net/powerbi/metadata/models" -Headers $headers -Method Get
#
# if ($result -and ($result.value))
# {
# Write-Output $result.value
# }
# else
# {
# Write-Output $result
# }
#}

#region Private Methods

Function Get-PowerBIRequestUrl{    
    [CmdletBinding()]    
    param(                                                    
        [Parameter(Mandatory=$true)] [string] $scope,        
        [Parameter(Mandatory=$false)] [switch] $beta = $false,    
        [Parameter(Mandatory=$false)] [switch] $ignoreGroup = $false    
    )
            
    $pbiAPIUrl = "https://api.powerbi.com/v1.0/myorg"            
    
    if ($beta)
    {
        $pbiAPIUrl = "https://api.powerbi.com/beta/myorg"
    }        
        
    $groupId = $script:pbiGroupId

    if ($ignoreGroup)
    {
        $groupId = $null
    }

    if ([string]::IsNullOrEmpty($groupId))
    {
        return "$pbiAPIUrl/$scope"
    }
    else
    {
        return "$pbiAPIUrl/groups/$groupId/$scope"
    }
    
}

Function Get-PBIDataSetTables{
    [CmdletBinding()]        
    param(                                    
        [Parameter(Mandatory=$true)] [string] $authToken,
        [Parameter(Mandatory=$true)] [string] $id,
        [Parameter(Mandatory=$true)] [string] $url
    )
            
    Write-Verbose "Getting DataSet '$id' Tables"
        
    try
    {    
        $result = Invoke-RestMethod -Uri "$url/$id/tables" -Headers $headers -Method Get
        
        Write-Output $result.value    
    }
    catch
    {
        Write-Warning "Cannot retrieve DataSet '$id' tables."
    }
}

Function ConvertTo-PBIJson{
    param(        
            $obj,
            [hashtable] $types
        )
        
    $jsonBody = $obj | ConvertTo-Json -Depth 4
    
    # If custom types are defined change them
    
    if ($types -ne $null -and $types.count -ne 0)
    {
        # Workaround to not have issues with DateTimes & ConvertTo-Json (http://stackoverflow.com/questions/26067906/format-a-datetime-in-powershell-to-json-as-date1411704000000)
    
        Write-Verbose "Changing dataset types"
                
        $jsonObj = ConvertFrom-Json $jsonBody
        
        $tables = $jsonObj.tables
        
        if (-not $tables)
        {    
            $tables = @($jsonObj)
        }
        
        $tables |% {
                $table = $_
                $table.columns |% {
                    
                    $typeKey = "$($table.name).$($_.name)"
                    
                    if ($types.containsKey($typeKey))
                    {
                        $_.dataType = $types[$typeKey]
                    }            
                }
            }
        
        $jsonBody = $jsonObj | ConvertTo-Json -Depth 4    
    }
    
    $jsonBody
}

Function ConvertTo-PBIDataSet($dataSet)
{
    $ds = @{
            name = $dataSet.DataSetName
            ; tables = $dataSet.Tables |%{
                
                $table = $_
                
                ConvertTo-PBITableFromDataTable $table                                    
            }                        
        }
        
    return $ds
}

Function ConvertTo-PBITableFromDataTable($table)
{                                                
    $pbiTable = @{ 
        name = $table.TableName
        ; columns = $table.Columns |% {
            $column = $_
            
            $columnTypeName = $column.DataType.Name
            
            $pbiTypeName = ConvertTo-PBIDataType $column.DataType.Name         
                                            
            return @{ name = $column.ColumnName; dataType = $pbiTypeName  }
        }                                                
    }                                            
        
    return $pbiTable
}

Function ConvertTo-PBITable($obj, $name)
{                
    $pbiTable = @{name = $name; columns = @()}
    
    if ($obj -is [System.Data.DataTable])
    {
        $pbiTable = ConvertTo-PBITableFromDataTable $obj                        
    }
    elseif($obj -is [array] -and $obj[0] -is [System.Data.DataRow])
    {
        $pbiTable = ConvertTo-PBITableFromDataTable $obj[0].Table
    }
    else
    {
        $sampleRow = $obj | Select -First 1                            
                
        if ($sampleRow -is [hashtable])
        {
            $properties = $sampleRow.Keys | Select @{N="Name";E={$_}}
        }            
        elseif ($sampleRow.PSStandardMembers.DefaultDisplayPropertySet)
        {
            $properties = $sampleRow | Get-Member -MemberType *Property -Name $sampleRow.PSStandardMembers.DefaultDisplayPropertySet.ReferencedPropertyNames    
        }
        else
        {
            $properties = $sampleRow | Get-Member -MemberType *Property
        }
                    
        $properties |% {
            
            $value = $sampleRow.$($_.Name)

            if ($value -ne $null)
            {
                $typeName = $value.GetType().Name
            
                $pbiDataType = ConvertTo-PBIDataType $typeName
            }
            else
            {
                $typeName = "string"
            }            
                            
            $pbiTable.columns += @{name = $_.Name; dataType = $pbiDataType}                
        }
    }                                    
        
    return $pbiTable
}

Function ConvertTo-PBITableData($data)
{            
    # DataTable already define the columns that are to be uploaded
    
    if ($data -is [System.Data.DataTable])
    {
        return $data
    }
    
    $sampleRow = $data | Select -First 1                            
            
    if ($sampleRow -is [System.Data.DataRow])
    {
        return (,$sampleRow.Table)
    }
    elseif ($sampleRow -is [hashtable])
    {                
        # Hashtable already defines the properties to send to PBI
        return $data
    }            
    elseif ($sampleRow.PSStandardMembers.DefaultDisplayPropertySet)
    {
        $properties = $sampleRow | Get-Member -MemberType *Property -Name $sampleRow.PSStandardMembers.DefaultDisplayPropertySet.ReferencedPropertyNames    
    }
    else
    {
        $properties = $sampleRow | Get-Member -MemberType *Property
    }
    
    $data = $data | select @($properties | Select -ExpandProperty Name)    
    
    return $data                
}

Function ConvertTo-PBIDataType($typeName, $errorIfNotCompatible = $true)
{            
    $pbiTypeName = switch -regex ($typeName) 
    { 
        "Int(?:\d{2})?" {"Int64"}
        "Double|Decimal" {"Double"}
        "Boolean" {"bool"}
        "Datetime" {"Datetime"}
        "String" {"String"}
        default {
            if ($errorIfNotCompatible)
            {
                throw "Type '$typeName' not supported in PowerBI"
            }            
        }
    }    
    
    return $pbiTypeName
}


Function Resolve-PowerBIAuthToken($authToken)
{
    if ([string]::IsNullOrEmpty($authToken))
    {
        $authToken = Get-PBIAuthToken
    }

    $authToken
}

Function Get-PowerBIRequestHeader($authToken)
{        
    $headers = @{
        'Content-Type'='application/json'
        'Authorization'= "Bearer $authToken"
        }
    
    return $headers
}

Function Assert-DataSetObjectSchema($dataSet)
{
    if (-not $dataSet.ContainsKey("name"))
    {
        throw "'dataSet.name' dont exists"
    }
    
    if (-not $dataSet.ContainsKey("tables"))
    {
        throw "'dataSet.tables' dont exists"
    }
    if (-not $dataSet.tables -is [array])
    {
        throw "'dataSet.tables' object must be an array"
    }
    
    $dataSet.tables |% {
    
        $table = $_
        
        Assert-DataSetTableObjectSchema $table
        
    }
}

Function Assert-DataSetTableObjectSchema($table)
{                
    if (-not $table.ContainsKey("name"))
    {
        throw "'table.name' dont exists"
    }
    
    if (-not $table.columns -is [array])
    {
        throw "'table.columns' object must be an array"
    }    
    
    $table.columns |% {
        $column = $_
        
        if (-not $column.ContainsKey("name"))
        {
            throw "'column.name' dont exists"
        }
        
        if (-not $column.ContainsKey("dataType"))
        {
            throw "'column.dataType' dont exists"
        }
    }    
}

Function Resolve-GroupId($authToken, $groupId, $groupName)
{        
    if (-not [string]::IsNullOrEmpty($groupName))
    {
        $groupId = @(Get-PBIGroup -authToken $authToken -name $groupName)[0].id
    }    
    
    return $groupId
}



#endregion