-
Notifications
You must be signed in to change notification settings - Fork 28
/
Copy pathSetDeviceProfile.v18.ps1
633 lines (488 loc) · 30.4 KB
/
SetDeviceProfile.v18.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
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
<# ----- About: ----
# N-able Backup Bulk Set Device Profile
# Revision v18 - 2021-10-11
# Author: Eric Harless, Head Backup Nerd - N-able
# Twitter @Backup_Nerd Email:eric.harless@n-able.com
# Reddit https://www.reddit.com/r/Nable/
# -----------------------------------------------------------#>
<# ----- Legal: ----
# Sample scripts are not supported under any N-able support program or service.
# The sample scripts are provided AS IS without warranty of any kind.
# N-able expressly disclaims all implied warranties including, warranties
# of merchantability or of fitness for a particular purpose.
# In no event shall N-able or any other party be liable for damages arising
# out of the use of or inability to use the sample scripts.
# -----------------------------------------------------------#>
<# ----- Compatibility: ----
# For use with the Standalone edition of N-able Backup
# -----------------------------------------------------------#> ## Compatibility
<# ----- Behavior: ----
# Check/ Get/ Store secure credentials
# Authenticate to https://backup.management console
# Selfcopy to ProgramData\MXB folder
# Enumerate Partners
# GUI Select Single Partner
# Enumerate Profiles
# GUI Select Single Profile
# Enumerate Account Statistics
# GUI Select Multiple Devices
# Set Selected Devices to Selected Profile
# Write to Log File
#
# Use the -Monitorlog parameter to display logs via seperate Powershell console
# Use the -ClearCredentials parameter to remove stored API credentials at start of script
#
# https://documentation.n-able.com/backup/userguide/documentation/Content/service-management/json-api/home.htm
# https://documentation.n-able.com/backup/userguide/documentation/Content/service-management/json-api/API-column-codes.htm
# -----------------------------------------------------------#>
[CmdletBinding()]
Param (
[Parameter(Mandatory=$False)] [switch]$ClearCredentials, ## Remove Stored API Credentials at start of script
[Parameter(Mandatory=$False)] [switch]$Monitorlog ## Display Logs via seperate Powershell Console
)
#region ----- Environment, Variables, Names and Paths ----
Clear-Host
Write-Output " Set Device Profiles`n`n"
$Syntax = Get-Command $PSCommandPath -Syntax ; Write-Output " Script Parameter Syntax:`n`n $Syntax"
$scriptpath = $MyInvocation.MyCommand.Path
$dir = Split-Path $scriptpath
Push-Location $dir
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
$Script:strLineSeparator = " ---------"
$CurrentDate = Get-Date -format "yyy-MM-dd_hh-mm-ss"
$urlJSON = 'https://api.backup.management/jsonapi'
#endregion ----- Environment, Variables, Names and Paths ----
#region ----- Functions ----
#region ----- Authentication ----
Function Set-APICredentials {
Write-Output $Script:strLineSeparator
Write-Output " Setting Backup API Credentials"
if (Test-Path $APIcredpath) {
Write-Output $Script:strLineSeparator
Write-Output " Backup API Credential Path Present" }else{ New-Item -ItemType Directory -Path $APIcredpath}
Write-Output $Script:strLineSeparator
Write-Output " Enter Exact, Case Sensitive Partner Name for N-able Backup.Management API i.e. 'Acme, Inc (bob@acme.net)'"
DO{ $PartnerName = Read-Host " Enter Login Partner Name" }
WHILE ($partnerName.length -eq 0)
$PartnerName | out-file $APIcredfile
$BackupCred = Get-Credential -UserName "" -Message 'Enter Login Email and Password for N-able Backup.Management API'
$BackupCred | Add-Member -MemberType NoteProperty -Name PartnerName -Value "$PartnerName"
$BackupCred.UserName | Out-file -append $APIcredfile
$BackupCred.Password | ConvertFrom-SecureString | Out-file -append $APIcredfile
Start-Sleep -milliseconds 300
Send-APICredentialsCookie ## Attempt API Authentication
} ## Set API credentials if not present
Function Get-APICredentials {
$Script:True_path = "C:\ProgramData\MXB\"
$Script:APIcredfile = join-path -Path $True_Path -ChildPath "$env:computername API_Credentials.Secure.txt"
$Script:APIcredpath = Split-path -path $APIcredfile
if (($ClearCredentials) -and (Test-Path $APIcredfile)) {
Remove-Item -Path $Script:APIcredfile
$ClearCredentials = $Null
Write-Output $Script:strLineSeparator
Write-Output " Backup API Credential File Cleared"
Send-APICredentialsCookie ## Retry Authentication
}else{
Write-Output $Script:strLineSeparator
Write-Output " Getting Backup API Credentials"
if (Test-Path $APIcredfile) {
Write-Output $Script:strLineSeparator
" Backup API Credential File Present"
$APIcredentials = get-content $APIcredfile
$Script:cred0 = [string]$APIcredentials[0]
$Script:cred1 = [string]$APIcredentials[1]
$Script:cred2 = $APIcredentials[2] | Convertto-SecureString
$Script:cred2 = [Runtime.InteropServices.Marshal]::PtrToStringAuto([Runtime.InteropServices.Marshal]::SecureStringToBSTR($Script:cred2))
Write-Output $Script:strLineSeparator
Write-output " Stored Backup API Partner = $Script:cred0"
Write-output " Stored Backup API User = $Script:cred1"
Write-output " Stored Backup API Password = Encrypted"
}else{
Write-Output $Script:strLineSeparator
Write-Output " Backup API Credential File Not Present"
Set-APICredentials ## Create API Credential File if Not Found
}
}
} ## Get API credentials if present
Function Send-APICredentialsCookie {
Get-APICredentials ## Read API Credential File before Authentication
$url = "https://api.backup.management/jsonapi"
$data = @{}
$data.jsonrpc = '2.0'
$data.id = '2'
$data.method = 'Login'
$data.params = @{}
$data.params.partner = $Script:cred0
$data.params.username = $Script:cred1
$data.params.password = $Script:cred2
$webrequest = Invoke-WebRequest -Method POST `
-ContentType 'application/json' `
-Body (ConvertTo-Json $data) `
-Uri $url `
-SessionVariable Script:websession `
-UseBasicParsing
$Script:cookies = $websession.Cookies.GetCookies($url)
$Script:websession = $websession
$Script:Authenticate = $webrequest | convertfrom-json
#Debug Write-output "$($Script:cookies[0].name) = $($cookies[0].value)"
if ($authenticate.visa) {
$Script:visa = $authenticate.visa
}else{
Write-Output $Script:strLineSeparator
Write-output " Authentication Failed: Please confirm your Backup.Management Partner Name and Credentials"
Write-output " Please Note: Multiple failed authentication attempts could temporarily lockout your user account"
Write-Output $Script:strLineSeparator
Set-APICredentials ## Create API Credential File if Authentication Fails
}
} ## Use Backup.Management credentials to Authenticate
#endregion ----- Authentication ----
#region ----- Data Conversion ----
Function Format-FileSize() {
Param ([int]$size)
If ($size -gt 1TB) {[string]::Format("{0:0.00} TB", $size / 1TB)}
ElseIf ($size -gt 1GB) {[string]::Format("{0:0.00} GB", $size / 1GB)}
ElseIf ($size -gt 1MB) {[string]::Format("{0:0.00} MB", $size / 1MB)}
ElseIf ($size -gt 1KB) {[string]::Format("{0:0.00} kB", $size / 1KB)}
ElseIf ($size -gt 0) {[string]::Format("{0:0.00} B", $size)}
Else {""}
}
Function Convert-UnixTimeToDateTime($inputUnixTime){
if ($inputUnixTime -gt 0 ) {
$epoch = Get-Date -Date "1970-01-01 00:00:00Z"
$epoch = $epoch.ToUniversalTime()
$epoch = $epoch.AddSeconds($inputUnixTime)
return $epoch
}else{ return ""}
} ## Convert epoch time to date time
Function Get-LogTimeStamp {
#Get-Date -format s
return "[{0:yyy-MM-dd} {0:HH:mm:ss}]" -f (Get-Date)
} ## Output proper timeStamp for log file
Function Set-Persistance {
# ----- Self Copy & Logging Logic ----
$Script:True_path = "C:\ProgramData\MXB\"
$Script:ScriptFull = $Script:myInvocation.MyCommand.path
$Script:ScriptPath = Split-Path -Parent $Script:MyInvocation.MyCommand.Path
$Script:ScriptFile = Split-Path -Leaf $Script:MyInvocation.MyCommand.Path
$Script:ScriptVer = [io.path]::GetFileNameWithoutExtension($Script:MyInvocation.MyCommand.Name)
$Script:ScriptBase = $ScriptVer -replace '\..*'
$Script:ScriptFinal = Join-Path -Path $True_path -ChildPath $ScriptBase | Join-Path -ChildPath $ScriptFile
$Script:ScriptLog = Join-Path -Path $True_path -ChildPath $ScriptBase | Join-Path -ChildPath "$ScriptBase.log"
$Script:ScriptLogParent = Split-path -path $ScriptLog
if (Test-Path $Script:ScriptLogParent) {
Write-Output $Script:strLineSeparator
Write-Output " ScriptLog Path Present" }else{ New-Item -ItemType Directory -Path $Script:ScriptLogParent}
#mkdir -Force $Script:ScriptLogParent
Write-Output $Script:strLineSeparator
$SetCompressed = Invoke-WmiMethod -Path "Win32_Directory.Name='$ScriptLogParent'" -Name compress
If (($SetCompressed.returnvalue) -eq 0) { " Log items successfully compressed" } else { " Something went wrong!" }
if (Test-Path $Script:ScriptLog) {
Write-Output $Script:strLineSeparator
Write-Output " Log File Present"
$Script:Scriptlogsize = Format-FileSize((Get-Item $Scriptlog).length)
}else{ New-Item -ItemType File -Path $Script:ScriptLog}
#Test-Path -Path $ScriptFull,$ScriptFinal,$scriptLog
If ($ScriptFull -eq $ScriptFinal) {
Write-Output $Script:strLineSeparator
Write-Output ' Script Already Running from Target Location'
Write-Output $Script:strLineSeparator
} Else {
Write-Output $Script:strLineSeparator
Write-Output ' Copying Script to Target Location'
Write-Output $Script:strLineSeparator
Copy-item -Path $ScriptFull -Destination $ScriptLogParent -Force
}
# ----- End Self Copy & Logging Logic ----
}
#endregion ----- Data Conversion ----
#region ----- Backup.Management JSON Calls ----
Function CallJSON($url,$object) {
$bytes = [System.Text.Encoding]::ASCII.GetBytes($object)
$web = [System.Net.WebRequest]::Create($url)
$web.Method = “POST”
$web.ContentLength = $bytes.Length
$web.ContentType = “application/json”
$stream = $web.GetRequestStream()
$stream.Write($bytes,0,$bytes.Length)
$stream.close()
$reader = New-Object System.IO.Streamreader -ArgumentList $web.GetResponse().GetResponseStream()
return $reader.ReadToEnd()| ConvertFrom-Json
$reader.Close()
}
Function Send-GetPartnerInfo ($PartnerName) {
$url = "https://api.backup.management/jsonapi"
$data = @{}
$data.jsonrpc = '2.0'
$data.id = '2'
$data.visa = $Script:visa
$data.method = 'GetPartnerInfo'
$data.params = @{}
$data.params.name = [String]$PartnerName
$webrequest = Invoke-WebRequest -Method POST `
-ContentType 'application/json' `
-Body (ConvertTo-Json $data -depth 5) `
-Uri $url `
-SessionVariable Script:websession `
-UseBasicParsing
$Script:cookies = $websession.Cookies.GetCookies($url)
$Script:websession = $websession
$Script:Partner = $webrequest | convertfrom-json
if (($Partner.result.result.Level -ne "Root") -and ($Partner.result.result.Level -ne "Sub-root") -and ($Partner.result.result.Level -ne "Distributor")) {
[String]$Script:Uid = $Partner.result.result.Uid
[int]$Script:PartnerId = [int]$Partner.result.result.Id
[String]$script:Level = $Partner.result.result.Level
[String]$Script:PartnerName = $Partner.result.result.Name
Write-Output $Script:strLineSeparator
Write-output " $PartnerName - $partnerId - $Uid"
Write-Output $Script:strLineSeparator
}else{
Write-Output $Script:strLineSeparator
Write-Host " Lookup for Root, Sub-root and Distributor Partner Level Not Allowed"
Write-Output $Script:strLineSeparator
$Script:PartnerName = Read-Host " Enter EXACT Case Sensitive Customer/ Partner displayed name to lookup i.e. 'Acme, Inc (bob@acme.net)'"
Send-GetPartnerInfo $Script:partnername
}
if ($partner.error) {
write-output " $($partner.error.message)"
$Script:PartnerName = Read-Host " Enter EXACT Case Sensitive Customer/ Partner displayed name to lookup i.e. 'Acme, Inc (bob@acme.net)'"
Send-GetPartnerInfo $Script:partnername
}
} ## get PartnerID and Partner Level
Function Send-EnumeratePartners {
# ----- Get Partners via EnumeratePartners -----
# (Create the JSON object to call the EnumeratePartners function)
$objEnumeratePartners = (New-Object PSObject | Add-Member -PassThru NoteProperty jsonrpc ‘2.0’ |
Add-Member -PassThru NoteProperty visa $Script:visa |
Add-Member -PassThru NoteProperty method ‘EnumeratePartners’ |
Add-Member -PassThru NoteProperty params @{
parentPartnerId = $PartnerId
fetchRecursively = "false"
fields = (0,10,1,5,17,18)
} |
Add-Member -PassThru NoteProperty id ‘1’)| ConvertTo-Json -Depth 3
# (Call the JSON Web Request Function to get the EnumeratePartners Object)
[array]$EnumeratePartnersSession = CallJSON $urlJSON $objEnumeratePartners
$Script:visa = $EnumeratePartnersSession.visa
#Write-Output $Script:strLineSeparator
#Write-Output " Using Visa:" $Script:visa
#Write-Output $Script:strLineSeparator
# (Added Delay in case command takes a bit to respond)
Start-Sleep -Milliseconds 100
# (Get Result Status of EnumerateAccountProfiles)
$EnumeratePartnersSessionErrorCode = $EnumeratePartnersSession.error.code
$EnumeratePartnersSessionErrorMsg = $EnumeratePartnersSession.error.message
# (Check for Errors with EnumeratePartners - Check if ErrorCode has a value)
if ($EnumeratePartnersSessionErrorCode) {
Write-Output $Script:strLineSeparator
Write-Output " EnumerateAccountPartnersSession Error Code: $EnumeratePartnersSessionErrorCode"
Write-Output " EnumerateAccountPartnersSession Message: $EnumeratePartnersSessionErrorMsg"
Write-Output $Script:strLineSeparator
Write-Output " Exiting Script"
# (Exit Script if there is a problem)
#Break Script
}
Else {
# (No error)
$Script:EnumeratePartnersSessionResults = $EnumeratePartnersSession.result.result | select-object Name,@{l='Id';e={($_.Id).tostring()}},Level,Externalcode
$Script:EnumeratePartnersSessionResults += @( [pscustomobject]@{Name=$PartnerName;Id=[string]$PartnerId;Level='<ParentPartner>'} )
$Script:SelectedPartner = $EnumeratePartnersSessionResults | Sort-object Level,Name | Select-Object Name,Id,Level,Externalcode |
Where-object {$_.name -notlike "001???????????????- Recycle Bin"} |
Out-Gridview -Title "Select a PARTNER from available PARTNERS to list available PROFILES" -OutputMode Single
if ($SelectedPartner.id -eq $null) {Write-output " Script Exited, No Changes Made`n"; exit}
Write-Output "$(Get-LogTimeStamp) Selected Partner = $($SelectedPartner.name) | $($SelectedPartner.id)" | Out-file $ScriptLog -append
Write-Output $Script:strLineSeparator
Write-Output " Selected Partner = $($SelectedPartner.name) | $($SelectedPartner.id)"
Write-Output $Script:strLineSeparator
}
# ----- End Get Partners via EnumeratePartners -----
}
Function Send-EnumerateAccountProfiles {
# ----- Get Profiles via EnumerateAccountProfiles -----
# (Create the JSON object to call the EnumerateAccountProfiles function)
$objEnumerateAccountProfiles = (New-Object PSObject | Add-Member -PassThru NoteProperty jsonrpc ‘2.0’ |
Add-Member -PassThru NoteProperty visa $Script:visa |
Add-Member -PassThru NoteProperty method ‘EnumerateAccountProfiles’ |
Add-Member -PassThru NoteProperty params @{partnerId=[int]$SelectedPartner.id } |
Add-Member -PassThru NoteProperty id ‘1’)| ConvertTo-Json -Depth 3
# (Call the JSON Web Request Function to get the EnumerateAccountProfiles Object)
[array]$EnumerateAccountProfilesSession = CallJSON $urlJSON $objEnumerateAccountProfiles
#$Script:visa = $EnumerateAccountProfilesSession.visa
#Write-Output $Script:strLineSeparator
#Write-Output " Using Visa:" $Script:visa
#Write-Output $Script:strLineSeparator
# (Added Delay in case command takes a bit to respond)
Start-Sleep -Milliseconds 100
# (Get Result Status of EnumerateAccountProfiles)
$EnumerateAccountProfilesSessionErrorCode = $EnumerateAccountProfilesSession.error.code
$EnumerateAccountProfilesSessionErrorMsg = $EnumerateAccountProfilesSession.error.message
# (Check for Errors with EnumerateAccountProfiles - Check if ErrorCode has a value)
if ($EnumerateAccountProfilesSessionErrorCode) {
Write-Output $Script:strLineSeparator
Write-Output " EnumerateAccountProfilesSession Error Code: $EnumerateAccountProfilesSessionErrorCode"
Write-Output " EnumerateAccountProfilesSession Message: $EnumerateAccountProfilesSessionErrorMsg"
Write-Output $Script:strLineSeparator
Write-Output " Exiting Script"
# (Exit Script if there is a problem)
#Break Script
}
Else {
# (No error)
$Script:EnumerateAccountProfilesSessionResults = $EnumerateAccountProfilesSession.result.result | select-object Name,@{l='Id';e={($_.Id).tostring()}}
$Script:EnumerateAccountProfilesSessionResults += @( [pscustomobject]@{Name='None';Id="0"})
$Script:SelectedProfile = $EnumerateAccountProfilesSessionResults | where-object {$_.id -ne "5038"} | select-object Name,@{l='Id';e={($_.Id).tostring()}} |
Out-Gridview -Title "Select a PROFILE from available PROFILES to later apply to selected DEVICES" -OutputMode Single | Sort-Object Name,Id
Write-Output "$(Get-LogTimeStamp) Selected Profile = $($SelectedProfile.name) | $($SelectedProfile.id)" | Out-file $ScriptLog -append
if ($SelectedProfile.id -eq $null) {Write-output " Script Exited, No Changes Made`n"; exit}
Write-Output $Script:strLineSeparator
Write-Output " Selected Profile = $($SelectedProfile.name)"
Write-Output $Script:strLineSeparator
}
}
Function Send-EnumerateAccountStatistics {
# ----- Get Devices via EnumerateAccountStatistics -----
$Filter = "((!(PF =~ '[??????????]* - ????????-????-????-????-????????????') AND !(AR =~ '001???????????????- Recycle Bin')) AND (OP != 'Documents') AND (AT != 2))"
$Columns = ('AU','AR','AN','OI','OP','OS','OT','PD','PF','PN','AT','MN','TS','AA843')
$MaxDeviceCount=3000
# (Create the JSON object to call the EnumerateAccountStatistics function)
$objEnumerateAccountStatistics = (New-Object PSObject | Add-Member -PassThru NoteProperty jsonrpc ‘2.0’ |
Add-Member -PassThru NoteProperty visa $Script:visa |
Add-Member -PassThru NoteProperty method ‘EnumerateAccountStatistics’ |
Add-Member -PassThru NoteProperty params @{
query = @{
PartnerId=[int]$SelectedPartner.id
Filter=$filter
Columns=$columns
StartRecordNumber = 0
RecordsCount=$MaxDeviceCount
Totals=("COUNT(AT==1)","SUM(T3)","SUM(US)")
}
}|
Add-Member -PassThru NoteProperty id ‘1’)| ConvertTo-Json -Depth 4
# (Call the JSON Web Request Function to get the EnumerateAccountStatistics Object)
[array]$Script:EnumerateAccountStatisticsSession = CallJSON $urlJSON $objEnumerateAccountStatistics
#$Script:visa = $EnumerateAccountStatisticsSession.visa
#$SessionResults = $EnumerateAccountStatisticsSession.result.result | select-object
#$SessionResults | out-gridview -PassThru
#Write-Output $Script:strLineSeparator
#Write-Output " Using Visa:" $Script:visa
#Write-Output $Script:strLineSeparator
# (Added Delay in case command takes a bit to respond)
Start-Sleep -Milliseconds 100
# (Get Result Status of EnumerateAccountStatistics)
$SessionErrorCode = $EnumerateAccountStatisticsSession.error.code
$SessionErrorMsg = $EnumerateAccountStatisticsSession.error.message
# (Check for Errors with EnumerateAccountStatistics - Check if ErrorCode has a value)
if ($SessionErrorCode) {
Write-Output $Script:strLineSeparator
Write-Output " EnumerateAccountStatistics Error Code: $SessionErrorCode"
Write-Output " EnumerateAccountStatistics Message: $SessionErrorMsg"
Write-Output $Script:strLineSeparator
Write-Output " Exiting Script"
# (Exit Script if there is a problem)
#Break Script
}
Else {
# (No error)
}
$DeviceDetail = @()
ForEach ( $Result in $EnumerateAccountStatisticsSession.result.result ) {
$DeviceDetail += New-Object -TypeName PSObject -Property @{ AccountID = [String]$Result.AccountId;
PartnerID = [string]$Result.PartnerId;
Account = $Result.Settings.AU -join '' ;
TimeStamp = Convert-UnixTimeToDateTime ($Result.Settings.TS -join '') ;
DeviceName = $Result.Settings.AN -join '' ;
MachineName = $Result.Settings.MN -join '' ;
PartnerName = $Result.Settings.AR -join '' ;
Reference = $Result.Settings.PF -join '' ;
Product = $Result.Settings.PN -join '' ;
ProductID = $Result.Settings.PD -join '' ;
Profile = $Result.Settings.OP -join '' ;
ProfileID = $Result.Settings.OI -join '' ;
OsType = $Result.Settings.OT -join '' ;
OS = $Result.Settings.OS -join '' ;
AccountType = $Result.Settings.AT -join '' ;
Notes = $Result.Settings.AA843 -join '' }
}
# (Summarize DeviceDetail)
Write-Output "$(Get-LogTimeStamp) Total Device Count = $($DeviceDetail.Count)" | Out-file $ScriptLog -append
Write-Output $Script:strLineSeparator
Write-Output " Total Device Count = $($DeviceDetail.Count)"
Write-Output $Script:strLineSeparator
#$DeviceDetail | out-gridview -PassThru | Export-Csv c:\data\Migration.csv -notype
#$DeviceDetail | select PartnerId,Reference,PartnerName,DeviceName,MachineName,AccountID,Product,Profile,OsType,Notes | out-gridview -PassThru | Export-Csv -delimiter "`t" c:\data\backupdevices.csv -notype
$Script:SelectedDevice = $DeviceDetail | Select-Object Account,PartnerId,Reference,PartnerName,DeviceName,MachineName,AccountID,Product,ProductID,AccountType,profileId,Profile,OS,OsType,Timestamp,Notes |
Out-Gridview -Title "Assign PROFILE | $($selectedProfile.name) | to selected DEVICES | use SHIFT to select multiple DEVICES" -OutputMode Multiple
$Script:SelectedDevice = $Script:SelectedDevice | sort-object DeviceName
Write-Output "$(Get-LogTimeStamp) Selected Device Count = $($Script:SelectedDevice.AccountId.count)" | Out-file $ScriptLog -append
if ($SelectedDevice.AccountId -eq $null) {Write-output " Script Exited, No Changes Made`n"; exit}
Write-Output $Script:strLineSeparator
Write-Output " Selected Device Count = $($Script:SelectedDevice.AccountId.Count)"
Write-Output $Script:strLineSeparator
}
Function Send-ModifyAccount {
# ----- ModifyAccount -----
# (Create the JSON object to call the ModifyAccount function)
Foreach ($Selection in $SelectedDevice) {
$objModifyAccount = (New-Object PSObject | Add-Member -PassThru NoteProperty jsonrpc ‘2.0’ |
Add-Member -PassThru NoteProperty visa $Script:visa |
Add-Member -PassThru NoteProperty method ‘ModifyAccount’ |
Add-Member -PassThru NoteProperty params @{
accountInfo = @{
Id=[int]$($Selection.AccountID)
ProfileId=[int]$($SelectedProfile.id)
}
} |
Add-Member -PassThru NoteProperty id ‘1’)| ConvertTo-Json -Depth 3
# (Call the JSON Web Request Function to get the ModifyAccount Object)
$ModifyAccountSession = CallJSON $urlJSON $objModifyAccount
#$Script:visa = $ModifyAccountSession.visa
#Write-Output $Script:strLineSeparator
#Write-Output " Using Visa:" $Script:visa
#Write-Output $Script:strLineSeparator
# (Added Delay in case command takes a bit to respond)
Start-Sleep -Milliseconds 100
# (Get Result Status of ModifyAccountSession)
$ModifyAccountSessionErrorCode = $ModifyAccountSession.error.code
$ModifyAccountSessionErrorMsg = $ModifyAccountSession.error.message
# (Check for Errors with ModifyAccountSession - Check if ErrorCode has a value)
if ($ModifyAccountSessionErrorCode) {
Write-Output $Script:strLineSeparator
Write-Output " ModifyAccountSession Error Code: $ModifyAccountSessionErrorCode"
Write-Output " ModifyAccountSession Message: $ModifyAccountSessionErrorMsg"
Write-Output $Script:strLineSeparator
Write-Output "$(Get-LogTimeStamp) | DEVICE | $($Selection.AccountID) | $($Selection.DeviceName) | ASSIGN PROFILE ERROR | $ModifyAccountSessionErrorMsg" | Out-file $ScriptLog -append
# (Exit Script if there is a problem)
#Break Script
}
Else {
# (No error)
Write-Output " Profile | $($SelectedProfile.Id) | $($SelectedProfile.Name) | Assigned to Device | $($Selection.AccountID) | $($Selection.DeviceName) | Old Profile | $($Selection.profileId) | $($Selection.Profile)"
Write-Output "$(Get-LogTimeStamp) Profile | $($SelectedProfile.Id) | $($SelectedProfile.Name) | Assigned to Device | $($Selection.AccountID) | $($Selection.DeviceName) | Old Profile | $($Selection.profileId) | $($Selection.Profile)" | Out-file $ScriptLog -append
}
}
}
#endregion ----- Backup.Management JSON Calls ----
Function Exit-Routine {
Write-Output $Script:strLineSeparator
Write-Output " NOTE: Profile changes may not be updated in the console or via API call until after"
Write-Output " offline devices reconnect, running jobs complete, or servers check-in."
Write-Output " Restarting the 'Backup Service Controller' service should force the update."
Write-Output $Script:strLineSeparator
Write-Output " Log file found here:"
Write-Output $Script:strLineSeparator
Write-Output " & $scriptlog"
Write-Output ""
Write-Output " $scriptlogsize"
Write-Output $Script:strLineSeparator
Start-Sleep -seconds 15
}
#endregion ----- Functions ----
Set-Persistance
Send-APICredentialsCookie
Send-GetPartnerInfo $Script:cred0
Send-EnumeratePartners
If ($Monitorlog) { invoke-expression "cmd /c start powershell -NoExit -Command {(Get-Host).ui.RawUI.WindowTitle=`" SET PROFILE LOG - $scriptlog `"; Get-Content $scriptlog -tail 2 -Wait }" }
Send-EnumerateAccountProfiles
Send-EnumerateAccountStatistics
Send-ModifyAccount
Exit-Routine