-
Notifications
You must be signed in to change notification settings - Fork 0
/
AGMPowerCLICommonFunctions.ps1
755 lines (669 loc) · 22.4 KB
/
AGMPowerCLICommonFunctions.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
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
Function Get-AGMAPIData ([String]$filtervalue,[String]$keyword, [string]$search,[int]$timeout,[string]$endpoint,[string]$extrarequests,[switch][alias("o")]$options,[switch]$itemoverride,[switch]$duration,[string]$datefields,[int]$limit,[string]$sort)
{
<#
.SYNOPSIS
Send a Get API call to an AGM
.DESCRIPTION
The Get-AGMAPIData connects to AGM to issue a Get
Normally this function is not called directly, but by another function, such as Get-AGMUser.
However power users can use this function to simplify their own scripts if they so choose.
.NOTES
Written by Anthony Vandewerdt
.EXAMPLE
Get-AGMAPIData -endpoint /application -filtervalue appname~smalldb -datefields "syncdate" -limit 1 -sort id:desc
Use the /application endpoint which is used to display applications and display applications with a name like smalldb,
but limit the output to one object and sort by id descending.
This sort means that if an application is returned it will be the most recently created one.
#>
if ( (!($AGMSESSIONID)) -or (!($AGMIP)) )
{
Get-AGMErrorMessage -messagetoprint "Not logged in or session expired. Please login using Connect-AGM"
return
}
if (!($endpoint))
{
$endpoint = Read-Host "AGM End point"
}
if ($endpoint[0] -ne "/")
{
$endpoint = "/" + $endpoint
}
if (!($extrarequests))
{
$extrarequests = ""
}
if ($filtervalue)
{
$fv = ""
$andsep = $filtervalue.Split("&") -notmatch '^\s*$'
foreach ($line in $andsep)
{
# remove any whitespace at the end
$trimm = $line.TrimEnd()
$secondwordequals = $trimm.Split("=") | Select-Object -skip 1
$secondwordnotequal = $trimm.Split("!") | Select-Object -skip 1
$secondwordgreater = $trimm.Split(">") | Select-Object -skip 1
$secondwordlesser = $trimm.Split("<") | Select-Object -skip 1
$secondwordfuzzy = $trimm.Split("~") | Select-Object -skip 1
if ($secondwordequals)
{
$firstword = $trimm.Split("=") | Select-Object -First 1
if ($datefields)
{
foreach ($field in $datefields.Split(","))
{
if ($field -eq $firstword)
{
$secondwordequals = Convert-ToUnixDate $secondwordequals
}
}
}
$fv = $fv + "&filter=" + $firstword + ":==" + [System.Web.HttpUtility]::UrlEncode($secondwordequals)
}
elseif ($secondwordnotequal)
{
$firstword = $trimm.Split("!") | Select-Object -First 1
if ($datefields)
{
foreach ($field in $datefields.Split(","))
{
if ($field -eq $firstword)
{
$secondwordgreater = Convert-ToUnixDate $secondwordgreater
}
}
}
$fv = $fv + "&filter=" + $firstword + ":!=" + [System.Web.HttpUtility]::UrlEncode($secondwordnotequal)
}
elseif ($secondwordgreater)
{
$firstword = $trimm.Split(">") | Select-Object -First 1
if ($datefields)
{
foreach ($field in $datefields.Split(","))
{
if ($field -eq $firstword)
{
$secondwordgreater = Convert-ToUnixDate $secondwordgreater
}
}
}
$fv = $fv + "&filter=" + $firstword + ":>=" + [System.Web.HttpUtility]::UrlEncode($secondwordgreater)
}
elseif ($secondwordlesser)
{
$firstword = $trimm.Split("<") | Select-Object -First 1
if ($datefields)
{
foreach ($field in $datefields.Split(","))
{
if ($field -eq $firstword)
{
$secondwordlesser = Convert-ToUnixDate $secondwordlesser
}
}
}
$fv = $fv + "&filter=" + $firstword + ":<=" + [System.Web.HttpUtility]::UrlEncode($secondwordlesser)
}
elseif ($secondwordfuzzy)
{
$firstword = $trimm.Split("~") | Select-Object -First 1
if ($datefields)
{
foreach ($field in $datefields.Split(","))
{
if ($field -eq $firstword)
{
$secondwordfuzzy = Convert-ToUnixDate $secondwordfuzzy
}
}
}
$fv = $fv + "&filter=" + $firstword + ":=|" + [System.Web.HttpUtility]::UrlEncode($secondwordfuzzy)
}
}
#$fv
}
else
{
$fv = ""
}
if ($keyword)
{
$kw = ""
$andsep = $keyword.Split("&") -notmatch '^\s*$'
foreach ($line in $andsep)
{
# remove any whitespace at the end
$trimm = $line.TrimEnd()
if ($trimm)
{
$kw = $kw + "&keyword=" + [System.Web.HttpUtility]::UrlEncode($trimm)
}
}
}
else
{
$kw = ""
}
if ($sort)
{
$commasplit = $sort.Split(",")
foreach ($line in $commasplit)
{
$order = $line.Split(":") | Select-Object -skip 1
if (!($order))
{
Get-AGMErrorMessage -messagetoprint "Please specify a sort order of asc or desc after a full colon, e.g. appname:asc or appname:desc"
return
}
elseif
(($order -ne "asc") -and ($order -ne "desc"))
{
Get-AGMErrorMessage -messagetoprint "Please specify a sort order of asc or desc after a full colon, e.g. appname:asc or appname:desc"
return
}
if (!($sortreq))
{
$sortreq = "&sort=" + [System.Web.HttpUtility]::UrlEncode($line)
}
else
{
$sortreq = $sortreq + "," + [System.Web.HttpUtility]::UrlEncode($line)
}
}
}
else
{
$sortreq = ""
}
if ($search)
{
$searchitem = "&search=" + [System.Web.HttpUtility]::UrlEncode($search)
}
else
{
$searchitem = ""
}
# default of 120 seconds may be too short
if (!($timeout))
{
$timeout = 120
}
# we always start at apistart of 0 which is the first result
$apistart = 0
# if somehow the default actmaxapilimit set at connect-act is gone, we set it again
if ( $agmmaxapilimit -eq "" )
{
$agmmaxapilimit = 0
}
# the api limit per command should be either 4096 or if the user set actmaxapilimit to a number 1-4095 then use that value
if (( $agmmaxapilimit -gt 0 ) -and ( $agmmaxapilimit -le 4096 ))
{
$maxlimitpercommand = $agmmaxapilimit
}
else
{
$maxlimitpercommand = 4096
}
# if user askedd for a limit lets use it
if (($limit) -and ($limit -ne 0))
{
$maxlimitpercommand = $limit
}
$method = "get"
if ($options)
{
$method = "options"
}
# time to send out endpoint
$done = 0
Do
{
Try
{
$url = "https://$AGMIP/actifio" + "$endpoint" + "?offset=" + "$apistart" + "&limit=$maxlimitpercommand" + "$fv" + "$searchitem" + "$kw" + "$sortreq" + "$extrarequests"
# write-host "we are going to use this method: $method with this url: $url"
if ($IGNOREAGMCERTS)
{
$resp = Invoke-RestMethod -SkipCertificateCheck -Method $method -Headers @{ Authorization = "Actifio $AGMSESSIONID" } -Uri "$url" -TimeoutSec $timeout
}
else
{
$resp = Invoke-RestMethod -Method $method -Headers @{ Authorization = "Actifio $AGMSESSIONID" } -Uri "$url" -TimeoutSec $timeout
}
}
Catch
{
if ( $((get-host).Version.Major) -gt 5 )
{
$RestError = $_
}
else
{
$result = $_.Exception.Response.GetResponseStream()
$reader = New-Object System.IO.StreamReader($result)
$reader.BaseStream.Position = 0
$reader.DiscardBufferedData()
$RestError = $reader.ReadToEnd();
}
}
if ($RestError)
{
Test-AGMJSON $RestError
}
else
{
if ( (!($resp.items)) -or ($itemoverride -eq $true) )
{
if ($options)
{
$grab = $resp | ConvertTo-JSON -depth 4 | ConvertFrom-Json -AsHashtable
if ($grab.Values)
{
$grab1 = $grab.Values.filterablefields | Sort-Object -property field
$grab2 = foreach ($line in $grab1) { write-host $line.field "(" $line.type ")" }
$grab2
}
}
else
{
# time stamp conversion
if ($datefields)
{
foreach ($field in $datefields.Split(","))
{
if ($resp.$field)
{
$resp.$field = Convert-FromUnixDate $resp.$field
}
}
}
if ($duration)
{
if ($resp.duration)
{
$resp.duration = Convert-AGMDuration $resp.duration
}
}
$resp
}
return
}
else
{
if ($datefields)
{
if ($resp.items)
{
foreach($line in $resp.items)
{
foreach ($field in $datefields.Split(","))
{
if ($line.$field)
{
$line.$field = Convert-FromUnixDate $line.$field
}
}
}
}
}
if ($duration)
{
if ($resp.items)
{
foreach($line in $resp.items)
{
if ($line.duration)
{
$line.duration = Convert-AGMDuration $line.duration
}
}
}
}
$resp.items
}
}
# count the results and add 4096 to apistart. If we got less than 4096 we are done and can finish by settting done to 1
$objcount = $resp.count
# if less than 4096 we are either finished or hit the max and we can drop out
if ( $objcount -lt 4096)
{
$done = 1
}
# we add 4096 by default for the next grab of data
else
{
$apistart = $apistart + 4096
$nextlimit = $apistart + 4096
}
if ( $apistart -eq $agmmaxapilimit)
{
$done = 1
}
# we now need to consider if the maxlimit should be trimmed
if (($agmmaxapilimit -gt 4096) -and ( $nextlimit -gt $agmmaxapilimit))
{
$maxlimitpercommand = $agmmaxapilimit - $apistart
}
}
while ($done -eq 0)
}
# errors can either have JSON and be easy to format or can be text, we need to sniff
Function Test-AGMJSON()
{
<#
.SYNOPSIS
Checks if data returned by AGM is JSON or not.
.DESCRIPTION
When AGM returns data it is normally in JSON which PowerShell 7 loves to munch on.
But sometimes data is not JSON or needs some special handling so this function checks what we got and handles it.
.NOTES
Written by Anthony Vandewerdt
#>
if ($args)
{
Try
{
$isthisjson = $args | Test-Json -ErrorAction Stop
$validJson = $true
}
Catch
{
$validJson = $false
}
if (!$validJson)
{
Write-Host "$args"
}
else
{
$testoutput = $args | ConvertFrom-JSON
# error messages from can Sky have multiple lines, which PS doesn't want to print, so we strip them out to get all the text
if ($testoutput.err_message)
{
$testoutput.err_message = $testoutput.err_message -replace "`n",","
}
if ($testoutput.err_code -eq 10011)
{
Get-AGMErrorMessage -messagetoprint "Not logged in or session expired. Please login using Connect-AGM"
}
$testoutput
}
Return
}
}
function Get-AGMErrorMessage ([string]$messagetoprint,[int]$errcode)
{
<#
.SYNOPSIS
Prints a message in a format that makes it looks like an error
.DESCRIPTION
When AGM returns an error you will get an errormessage and often an errorcode.
But if the module itself generates an error we want it to look like a proper error with the same format.
This also makes it easy to script, by looking for errormessage in returned data.
.NOTES
Written by Anthony Vandewerdt
#>
$acterror = @()
$acterrorcol = "" | Select-Object errormessage
$acterrorcol.errormessage = "$messagetoprint"
$acterror = $acterror + $acterrorcol
$acterror
}
Function Post-AGMAPIData ([int]$timeout,[string]$endpoint,[string]$body,[string]$method,[string]$datefields)
{
<#
.SYNOPSIS
Send a Post API call to an AGM
.DESCRIPTION
The Post-AGMAPIData connects to AGM to issue a Post
Normally this function is not called directly, but by another function.
However power users can use this function to simplify their own scripts if they so choose.
.NOTES
Written by Anthony Vandewerdt
.EXAMPLE
Post-AGMAPIData -endpoint /org -body '{ "description": "Melbourne test team","name": "MelTeam1" }' -datefields "modifydate,createdate"
In this example we send some JSON to the /org endpoint which requests a new org with the relevant name and description.
This will create an org and return data relevant to that new org. Note the returned data will be formatted JSON.
.EXAMPLE
Post-AGMAPIData -endpoint /org/53688920 -method "delete"
This deletes Org ID 53688920
#>
if ( (!($AGMSESSIONID)) -or (!($AGMIP)) )
{
Get-AGMErrorMessage -messagetoprint "Not logged in or session expired. Please login using Connect-AGM"
return
}
if (!($endpoint))
{
$endpoint = Read-Host "AGM End point"
}
if ($endpoint[0] -ne "/")
{
$endpoint = "/" + $endpoint
}
# default of 120 seconds may be too short
if (!($timeout))
{
$timeout = 120
}
# we need to set the method
if (!($method))
{
$method = "post"
}
if (!($body))
{
$body = '{ "accept": "*/*" }'
}
Try
{
$url = "https://$AGMIP/actifio" + "$endpoint"
# write-host "we are going to use this method: $method with this url: $url"
if ($IGNOREAGMCERTS)
{
$resp = Invoke-RestMethod -SkipCertificateCheck -Method $method -Headers @{ Authorization = "Actifio $AGMSESSIONID" ; accept = "application/json" } -body $body -ContentType "application/json" -Uri "$url" -TimeoutSec $timeout
}
else
{
$resp = Invoke-RestMethod -Method $method -Headers @{ Authorization = "Actifio $AGMSESSIONID" ; accept = "application/json" } -body $body -ContentType "application/json" -Uri "$url" -TimeoutSec $timeout
}
}
Catch
{
if ( $((get-host).Version.Major) -gt 5 )
{
$RestError = $_
}
else
{
$result = $_.Exception.Response.GetResponseStream()
$reader = New-Object System.IO.StreamReader($result)
$reader.BaseStream.Position = 0
$reader.DiscardBufferedData()
$RestError = $reader.ReadToEnd();
}
}
if ($RestError)
{
Test-AGMJSON $RestError
}
else
{
if ($resp)
{
# time stamp conversion
if ($datefields)
{
foreach ($field in $datefields.Split(","))
{
if ($resp.$field)
{
$resp.$field = Convert-FromUnixDate $resp.$field
}
}
}
$resp
}
}
}
Function Put-AGMAPIData ([int]$timeout,[string]$endpoint,[string]$body)
{
<#
.SYNOPSIS
Send a Put API call to an AGM
.DESCRIPTION
The Put-AGMAPIData connects to AGM to issue a Put
Normally this function is not called directly, but by another function.
However power users can use this function to simplify their own scripts if they so choose.
.NOTES
Written by Anthony Vandewerdt
.EXAMPLE
Put-AGMAPIData -endpoint /job/12345 -body '{ "status": "cancel" }'
This sends a Put API to the /job endpoint requesting that job ID 12345 be cancelled.
#>
if ( (!($AGMSESSIONID)) -or (!($AGMIP)) )
{
Get-AGMErrorMessage -messagetoprint "Not logged in or session expired. Please login using Connect-AGM"
return
}
if (!($endpoint))
{
$endpoint = Read-Host "AGM End point"
}
if ($endpoint[0] -ne "/")
{
$endpoint = "/" + $endpoint
}
# default of 120 seconds may be too short
if (!($timeout))
{
$timeout = 120
}
if (!($body))
{
$body = '{ "accept": "*/*" }'
}
Try
{
$url = "https://$AGMIP/actifio" + "$endpoint"
# write-host "we are going to use this method: $method with this url: $url"
if ($IGNOREAGMCERTS)
{
$resp = Invoke-RestMethod -SkipCertificateCheck -Method put -Headers @{ Authorization = "Actifio $AGMSESSIONID" } -body $body -ContentType "application/json" -Uri "$url" -TimeoutSec $timeout
}
else
{
$resp = Invoke-RestMethod -Method put -Headers @{ Authorization = "Actifio $AGMSESSIONID" } -body $body -ContentType "application/json" -Uri "$url" -TimeoutSec $timeout
}
}
Catch
{
if ( $((get-host).Version.Major) -gt 5 )
{
$RestError = $_
}
else
{
$result = $_.Exception.Response.GetResponseStream()
$reader = New-Object System.IO.StreamReader($result)
$reader.BaseStream.Position = 0
$reader.DiscardBufferedData()
$RestError = $reader.ReadToEnd();
}
}
if ($RestError)
{
Test-AGMJSON $RestError
}
else
{
if ($resp)
{
# time stamp conversion
if ($datefields)
{
foreach ($field in $datefields.Split(","))
{
if ($resp.$field)
{
$resp.$field = Convert-FromUnixDate $resp.$field
}
}
}
$resp
}
}
}
Function Convert-FromUnixDate ($UnixDate)
{
<#
.SYNOPSIS
Converts time stamps from Epoch to IS08601
.DESCRIPTION
By default AGM returns all date stamps as Epoch (seconds offset from Jan 1, 1970).
Fields can look like this: syncdate=1594697898434000
Humans prefer dates that are human readable and really cool humans prefer ISO8601 format.
.NOTES
Written by Anthony Vandewerdt
.EXAMPLE
Convert-FromUnixDate 1594697896759000
Convert 1594697896759000 to ISO8601 readable date format
#>
if (!($UnixDate))
{
$UnixDate = Read-Host "Unix date"
}
if ($AGMTimezone -eq "local")
{
[timezone]::CurrentTimeZone.ToLocalTime(([datetime]'1/1/1970').AddSeconds($UnixDate.ToString().SubString(0,10))).ToLocalTime().ToString('yyyy-MM-dd HH:mm:ss')
}
if ($AGMTimezone -eq "utc")
{
[timezone]::CurrentTimeZone.ToLocalTime(([datetime]'1/1/1970').AddSeconds($UnixDate.ToString().SubString(0,10))).ToUniversalTime().ToString('yyyy-MM-dd HH:mm:ss')
}
}
Function Convert-ToUnixDate ([datetime]$InputEpoch)
{
<#
.SYNOPSIS
Converts time stamps from IS08601 to Epoch
.DESCRIPTION
By default AGM prefers to munch on date stamps that are in Epoch (seconds offset from Jan 1, 1970).
Humans prefer dates that are human readable so this function lets everyone be happy.
.NOTES
Written by Anthony Vandewerdt
#>
if ($AGMTimezone -eq "local")
{
[datetime]$Epoch = [timezone]::CurrentTimeZone.ToLocalTime([datetime]'1/1/1970')
$Ctime = (New-TimeSpan -Start $Epoch -End $InputEpoch).TotalSeconds
$Ctime = $Ctime * 1000000
$Ctime -as [decimal]
}
if ($AGMTimezone -eq "utc")
{
[datetime]$Epoch = '1970-01-01 00:00:00'
$Ctime = (New-TimeSpan -Start $Epoch -End $InputEpoch).TotalSeconds
$Ctime = $Ctime * 1000000
$Ctime -as [decimal]
}
}
Function Convert-AGMDuration ($duration)
{
<#
.SYNOPSIS
Creates a human readable duration timestamps
.DESCRIPTION
Duration is returned by AGM as seconds. So we turn that into HHH:MM:SS
.NOTES
Written by Anthony Vandewerdt
#>
$convertedtime = [timespan]::fromseconds($duration/1000000)
[string]$totalhours = $convertedtime.days * 24 + $convertedtime.hours
if ($totalhours -eq "0")
{
$totalhours = "00"
}
$totalhours + $convertedtime.ToString("\:mm\:ss")
}