-
Notifications
You must be signed in to change notification settings - Fork 321
/
Copy pathMoveTenantMedia.ps1
279 lines (241 loc) · 10.6 KB
/
MoveTenantMedia.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
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
Import-Module "MSAL.PS"
# These value can be found on the Business Central Admin Center
$script:SourceEnvironmentUlr = 'PROVIDEVALUE' # E.g. "https://api.businesscentral.dynamics.com/v2.0/a5876f8b-c580-4861-823a-ecfda5e99d94/MySandbox/api/MSFT/moveData/v1.0/companies"
$script:TargetEnvironmentUlr = 'PROVIDEVALUE' # E.g."https://api.businesscentral.dynamics.com/v2.0/a5876f8b-c580-4861-823a-ecfda5e99d94/Production/api/MSFT/moveData/v1.0/companies"
$script:AADTenantID = "PROVIDEVALUE" # e.g. a5876f8b-c580-4861-823a-ecfda5e99d94"
# OAuth2 App parameters - Register your app and update to match - Values can be found on portal.azure.com
$script:ClientId = "PROVIDEVALUE" # e.g. 3f65a4a6-af4c-4b7a-92a9-5b2fcde8f428
$script:RedirectUri = "PROVIDEVALUE" # e.g, "https://login.microsoftonline.com/common/oauth2/nativeclient"
# End of the values to provide
$script:BaseAuthorityUri = "https://login.microsoftonline.com"
$script:BcAppIdUri = "https://api.businesscentral.dynamics.com"
$script:BcScopes = @("$BcAppIdUri/user_impersonation", "$BcAppIdUri/Financials.ReadWrite.All" )
$script:AuthorityUri = "$BaseAuthorityUri/$AadTenantId"
$script:DefaultAuthrization = 'Bearer'
$script:TokenExpirationTime = (Get-Date)
function Copy-TenantMedia
(
[int] $startIndex = 0, # Use this parameters if you want to run the script in parallel. Start the first scripts by specifying e.g. $maxCount 10.000 and second script with $startIndex 10.000 and $maxCount 10.000
[int] $maxCount = 0,
[bool] $transferMediaSets = $false
)
{
# Setup URLs
Write-Host "Connecting to the environments"
$sourceCompanyId = Get-SourceCompanyURL -EnvironmentUlr $script:SourceEnvironmentUlr
$sourceMediaAPIUrl = $script:SourceEnvironmentUlr + '(' + $sourceCompanyId + ')/tenantMedia'
$sourceMediaIDsAPIUrl = $script:SourceEnvironmentUlr + '(' + $sourceCompanyId + ')/tenantMediaIds'
$sourceMediaSetAPIUrl = $script:SourceEnvironmentUlr + '(' + $sourceCompanyId + ')/tenantMediaSet'
$sourceMediaSetIDsAPIUrl = $script:SourceEnvironmentUlr + '(' + $sourceCompanyId + ')/tenantMediaSetIds'
Write-Host "Using company with ID $sourceCompanyId as source"
$targetCompanyId = Get-SourceCompanyURL -EnvironmentUlr $script:TargetEnvironmentUlr
$targetMediaAPIUrl = $script:TargetEnvironmentUlr + '(' + $targetCompanyId + ')/tenantMedia'
$targetMediaIDsAPIUrl = $script:TargetEnvironmentUlr + '(' + $targetCompanyId + ')/tenantMediaIds'
$targetMediaSetAPIUrl = $script:TargetEnvironmentUlr + '(' + $targetCompanyId + ')/tenantMediaSet'
$targetMediaSetIDsAPIUrl = $script:TargetEnvironmentUlr + '(' + $targetCompanyId + ')/tenantMediaSetIds'
Write-Host "Using company with ID $targetCompanyId as target"
# Get Tenant Media Records to copy
Write-Host "Discovering tenant media records to move"
$sourceTenantMediaIDs = Get-TenantMediaIDs -MediaIDsAPIUrl $sourceMediaIDsAPIUrl
[System.Collections.ArrayList] $itemsToMove = $sourceTenantMediaIDs | Select-Object -Property id | Sort-Object -Property id
$MediaSetitemsToMove = [System.Collections.ArrayList]@()
if ($transferMediaSets)
{
$sourceTenantMediaSetIDs = Get-TenantMediaIDs -MediaIDsAPIUrl $sourceMediaSetIDsAPIUrl
$MediaSetitemsToMove = $sourceTenantMediaSetIDs | Select-Object -Property id | Sort-Object -Property id
}
$targetTenantMediaIDs = Get-TenantMediaIDs -MediaIDsAPIUrl $targetMediaIDsAPIUrl
$ExistingTenantMedia = New-Object System.Collections.Specialized.OrderedDictionary
if($targetTenantMediaIDs)
{
if($targetTenantMediaIDs.value.Count -gt 0)
{
[System.Collections.ArrayList] $targetTenantMediaIDs = $targetTenantMediaIDs | Select-Object -Property id | Sort-Object -Property id
for ($i = 0; $i -lt $targetTenantMediaIDs.Count; $i++)
{
$ExistingTenantMedia.Add($targetTenantMediaIDs[$i].id,'')
}
}
}
$ExistingTenantMediaSets = New-Object System.Collections.Specialized.OrderedDictionary
if ($transferMediaSets)
{
$targetTenantMediaSetIDs = Get-TenantMediaIDs -MediaIDsAPIUrl $targetMediaSetIDsAPIUrl
if($targetTenantMediaSetIDs)
{
if($targetTenantMediaSetIDs.value.Count -gt 0)
{
[System.Collections.ArrayList] $targetTenantMediaSetIDs = $targetTenantMediaSetIDs | Select-Object -Property id | Sort-Object -Property id
for ($i = 0; $i -lt $targetTenantMediaSetIDs.Count; $i++)
{
$ExistingTenantMediaSets.Add($targetTenantMediaSetIDs[$i].id,'')
}
}
}
}
$endIndexOfItemsToMove = $itemsToMove.Count
if($maxCount)
{
$endIndexOfItemsToMove = $startIndex + $maxCount
}
# Move selected records
for($i = $startIndex; $i -le $endIndexOfItemsToMove; $i++)
{
$mediaIDToMove = $itemsToMove[$i].id
if (-not $ExistingTenantMedia.Contains($itemsToMove[$i].id))
{
$sourceURl = $sourceMediaAPIUrl + '(' + $mediaIDToMove + ')'
$Token = Get-AADToken
$sourceResponse = Invoke-GetMethod -Uri $sourceURl -Token $Token
$tenantMediaBody = @{
id="$($sourceResponse.id)";
companyName=$($sourceResponse.companyName);
creatingUser=$($sourceResponse.creatingUser);
description=$($sourceResponse.description);
expirationDate=$($sourceResponse.expirationDate);
fileName=$($sourceResponse.fileName);
height=$($sourceResponse.height);
base64ContentTxt=$($sourceResponse.base64ContentTxt);
mimeType=$($sourceResponse.mimeType);
prohibitCache=$($sourceResponse.prohibitCache);
securityToken=$($sourceResponse.securityToken);
width=$($sourceResponse.width);
}
Write-Host "Moving Media with ID " $tenantMediaBody.id " File Name " $tenantMediaBody.fileName
$response = Invoke-PostMethod -Uri $targetMediaAPIUrl -Token $Token -Body $tenantMediaBody
}
}
if ($transferMediaSets)
{
$endIndexOfItemSetssToMove = $MediaSetitemsToMove.Count
if($maxCount)
{
$endIndexOfItemSetssToMove = $startIndex + $maxCount
}
# Move selected records
for($i = $startIndex; $i -le $endIndexOfItemSetssToMove; $i++)
{
$mediaIDToMove = $MediaSetitemsToMove[$i].id
if (-not $ExistingTenantMediaSets.Contains($MediaSetitemsToMove[$i].id))
{
$sourceURl = $sourceMediaSetAPIUrl + '(' + $mediaIDToMove + ')'
$Token = Get-AADToken
$sourceResponse = Invoke-GetMethod -Uri $sourceURl -Token $Token
$tenantMediaBody = @{
id="$($sourceResponse.id)";
companyName=$($sourceResponse.companyName);
mediaID=$($sourceResponse.mediaID);
base64ContentTxt=$($sourceResponse.base64ContentTxt);
}
Write-Host "Moving Media with ID " $tenantMediaBody.id " File Name " $tenantMediaBody.fileName
$response = Invoke-PostMethod -Uri $targetMediaSetAPIUrl -Token $Token -Body $tenantMediaBody
}
}
}
}
function Get-TenantMediaIDs
(
[string] $MediaIDsAPIUrl
)
{
$Token = Get-AADToken
$response = Invoke-GetMethod -Uri $MediaIDsAPIUrl -Token $Token
[System.Collections.ArrayList] $TenantMediaIDs = $response.value
while($response.'@odata.nextLink')
{
$Token = Get-AADToken
$response = Invoke-GetMethod -Uri ($response.'@odata.nextLink') -Token $Token
$TenantMediaIDs.AddRange($response.value)
}
return $TenantMediaIDs
}
function Get-SourceCompanyURL
(
[string] $EnvironmentUlr
)
{
$Token = Get-AADToken
$response = Invoke-GetMethod -Uri $EnvironmentUlr -Token $Token
if (@($Response.value).Count -le 1)
{
$companyId = $Response.value.id
}
else
{
$companyId = $Response.value[0].id
}
return $companyId
}
function Invoke-GetMethod
(
[string] $Uri,
[string] $Token,
[string] $Authorization = $script:DefaultAuthrization
)
{
$response = Invoke-RestMethod -Method GET -Uri $Uri -Headers (Create-AuthorizationHeader -Token $Token -Authorization $Authorization)
return $response
}
function Invoke-PostMethod
(
[string] $Uri,
[string] $Token,
[string] $Authorization = $script:DefaultAuthrization,
$Body
)
{
$headers = Create-AuthorizationHeader -Token $Token -Authorization $Authorization;
try
{
$response = Invoke-RestMethod -Method POST -Uri $Uri -Headers $headers -Body (convertto-json $Body) -ContentType "application/json"
}
catch
{
Write-Host "Failed:" $Uri -ForegroundColor Red
Write-Host "StatusCode:" $_.Exception.Response.StatusCode.value__ -ForegroundColor Red
$responseStream = $_.Exception.Response.GetResponseStream()
$responseStream.Position = 0;
$streamReader = New-Object System.IO.StreamReader($responseStream)
$errorMessage = $streamReader.ReadToEnd()
$streamReader.Close()
$responseStream.Close()
Write-Host "Message: $errorMessage" -ForegroundColor Red
}
return $response
}
function Get-AADToken
(
[string] $UserName = $script:CurrentUserName,
[string] $Password = $script:CurrentPassword,
[string] $AADTenantID = $script:AADTenantID,
[string] $Version = "v1.0"
)
{
if($script:TokenExpirationTime)
{
if ($script:TokenExpirationTime -gt (Get-Date))
{
return $script:CurrentToken
}
}
try
{
$securePassword = ConvertTo-SecureString $Password -AsPlainText -Force
$UserCredential = New-Object System.Management.Automation.PSCredential($UserName, $securePassword)
$AuthenticationResult = Get-MsalToken -ClientId $script:ClientId -RedirectUri $script:RedirectUri -TenantId $AADTenantID -Authority $script:AuthorityUri -UserCredential $UserCredential -Scopes $script:BcScopes
}
catch {
$AuthenticationResult = Get-MsalToken -ClientId $script:ClientId -RedirectUri $script:RedirectUri -TenantId $AADTenantID -Authority $script:AuthorityUri -Prompt SelectAccount -Scopes $script:BcScopes
}
$script:CurrentToken = $AuthenticationResult.AccessToken;
$script:TokenExpirationTime = ($AuthenticationResult.ExpiresOn - (New-TimeSpan -Minutes 3))
return $AuthenticationResult.AccessToken;
}
function Create-AuthorizationHeader
(
[string] $Token,
[string] $Authorization = $script:DefaultAuthrization
)
{
return @{"Authorization"=$Authorization + " " + $Token;}
}