forked from RuiRomano/pbimonitor
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Fetch - Graph.ps1
194 lines (138 loc) · 5.37 KB
/
Fetch - Graph.ps1
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
param(
[psobject]$config
)
#region Graph API Helper Functions
function Get-AuthToken {
[cmdletbinding()]
param
(
[string]
$authority = "https://login.microsoftonline.com",
[string]
$tenantid,
[string]
$appid,
[string]
$appsecret ,
[string]
$resource
)
write-verbose "getting authentication token"
$granttype = "client_credentials"
$tokenuri = "$authority/$tenantid/oauth2/token?api-version=1.0"
$appsecret = [System.Web.HttpUtility]::urlencode($appsecret)
$body = "grant_type=$granttype&client_id=$appid&resource=$resource&client_secret=$appsecret"
$token = invoke-restmethod -method post -uri $tokenuri -body $body
$accesstoken = $token.access_token
write-output $accesstoken
}
function Read-FromGraphAPI {
[CmdletBinding()]
param
(
[string]
$url,
[string]
$accessToken,
[string]
$format = "JSON"
)
#https://blogs.msdn.microsoft.com/exchangedev/2017/04/07/throttling-coming-to-outlook-api-and-microsoft-graph/
try {
$headers = @{
'Content-Type' = "application/json"
'Authorization' = "Bearer $accessToken"
}
$result = Invoke-RestMethod -Method Get -Uri $url -Headers $headers
if ($format -eq "CSV") {
ConvertFrom-CSV -InputObject $result | Write-Output
}
else {
Write-Output $result.value
while ($result.'@odata.nextLink') {
$result = Invoke-RestMethod -Method Get -Uri $result.'@odata.nextLink' -Headers $headers
Write-Output $result.value
}
}
}
catch [System.Net.WebException] {
$ex = $_.Exception
try {
$statusCode = $ex.Response.StatusCode
if ($statusCode -eq 429) {
$message = "429 Throthling Error - Sleeping..."
Write-Host $message
Start-Sleep -Seconds 1000
}
else {
if ($ex.Response -ne $null) {
$statusCode = $ex.Response.StatusCode
$stream = $ex.Response.GetResponseStream()
$reader = New-Object System.IO.StreamReader($stream)
$reader.BaseStream.Position = 0
$reader.DiscardBufferedData()
$errorContent = $reader.ReadToEnd()
$message = "$($ex.Message) - '$errorContent'"
}
else {
$message = "$($ex.Message) - 'Empty'"
}
}
Write-Error -Exception $ex -Message $message
}
finally {
if ($reader) { $reader.Dispose() }
if ($stream) { $stream.Dispose() }
}
}
}
#endregion
try {
Write-Host "Starting Graph API Fetch"
$stopwatch = [System.Diagnostics.Stopwatch]::new()
$stopwatch.Start()
Add-Type -AssemblyName System.Web
$rootOutputPath = "$($config.OutputPath)\graph"
$outputPath = ("$rootOutputPath\{0:yyyy}\{0:MM}\{0:dd}" -f [datetime]::Today)
# ensure folder
New-Item -ItemType Directory -Path $outputPath -ErrorAction SilentlyContinue | Out-Null
$graphUrl = "https://graph.microsoft.com/beta"
$apiResource = "https://graph.microsoft.com"
$graphCalls = @(
@{
GraphUrl = "$graphUrl/users?`$select=id,displayName,assignedLicenses,UserPrincipalName";
FilePath = "$outputPath\users.json"
}
,
@{
GraphUrl = "$graphUrl/subscribedSkus?`$select=id,capabilityStatus,consumedUnits,prepaidUnits,skuid,skupartnumber,prepaidUnits";
FilePath = "$outputPath\subscribedskus.json"
}
)
foreach ($graphCall in $graphCalls)
{
Write-Host "Getting OAuth token"
$authToken = Get-AuthToken -resource $apiResource -appid $config.ServicePrincipal.AppId -appsecret $config.ServicePrincipal.AppSecret -tenantid $config.ServicePrincipal.TenantId
Write-Host "Calling Graph API: '$($graphCall.GraphUrl)'"
$data = Read-FromGraphAPI -accessToken $authToken -url $graphCall.GraphUrl | select * -ExcludeProperty "@odata.id"
Write-Host "Writing to file: '$($graphCall.FilePath)'"
ConvertTo-Json @($data) -Compress -Depth 5 | Out-File $graphCall.FilePath -Force
if ($config.StorageAccountConnStr) {
Write-Host "Writing to Blob Storage"
$storageRootPath = "$($config.StorageAccountContainerRootPath)/graph"
$outputFilePath = $graphCall.FilePath
if (Test-Path $outputFilePath)
{
Add-FileToBlobStorage -storageAccountConnStr $config.StorageAccountConnStr -storageContainerName $config.StorageAccountContainerName -storageRootPath $storageRootPath -filePath $outputFilePath -rootFolderPath $rootOutputPath
Remove-Item $outputFilePath -Force
}
else {
Write-Host "Cannot find file '$outputFilePath'"
}
}
}
}
finally {
$stopwatch.Stop()
Write-Host "Ellapsed: $($stopwatch.Elapsed.TotalSeconds)s"
}