-
-
Notifications
You must be signed in to change notification settings - Fork 19
/
PS-NCentral.psm1
4778 lines (4007 loc) · 284 KB
/
PS-NCentral.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
## PowerShell Module for N-Central(c) by N-Able
##
## Version : 1.6
## Author : Adriaan Sluis ([email protected])
##
## !Still some Work In Progress!
##
## Provides a PowerShell Interface for N-Central(c)
## Uses the SOAP-API of N-Central(c) by N-Able
## Completely written in PowerShell for easy reference/analysis.
##
##Copyright 2022 Tosch Automatisering
##
##Licensed under the Apache License, Version 2.0 (the "License");
##you may not use this file except in compliance with the License.
##You may obtain a copy of the License at
##
## http://www.apache.org/licenses/LICENSE-2.0
##
##Unless required by applicable law or agreed to in writing, software
##distributed under the License is distributed on an "AS IS" BASIS,
##WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
##See the License for the specific language governing permissions and
##limitations under the License.
##
## Change log
##
## v1.2 Feb 24, 2021
## -Made PowerShell 7 compatible by removing usage of WebServiceProxy.
## -Sorting CustomProperty-columns by default (NoSort/UnSorted Option available)
## -JWT-option in New-NCentralConnection
##
## v1.3 Mar 23, 2022
## -CustomProperty - Get individual Property Values. (Was list-only)
## -CustomProperty - Add/Remove individual (Comma-separated) values inside the CP.
## -CustomProperty - Optional Base64 Encoding/Decoding.
## -CustomerDetails - ValidationList for standard-/custom-property filled by API-query.
## -Enhanced Get-NCAccessGroupList/Detail
## -Enhanced Get-NCUserRoleList/Detail
##
## v1.4 May 20,2022
## -(issue) NCActiveIssueList -Status 1 and 5 were swapped. -Added NotifStateTxt-field
## -(issue) NCDeviceInfo - Multiple-values now shown comma-separated (was only showing first entry)
## -NCDeviceObject - Options to Include/Exclude categories
## -Optimized API-calls for multiple objects where supported (NCDeviceInfo and NCCDeviceObject)
## -ShowProgress option for NCDeviceInfo and NCDeviceObject using optimized API-calls.
## -Date/Time properties now have date-format (was String)
## -NCHelp shows a list of statuscodes at the bottom. (.NCStatus)
##
## v1.5 june 29, 2022
## -(issue) NCDevicePropertyList and NCCustomerPropertylist - Error on property-names containing spaces.
## -Optimized API-calls for multiple objects where supported (NCDevicePropertyList and NCCustomerPropertylist added)
## -NCCustomerPropertylist - Full-option to include basic properties
## -Backup-NCCustomProperties - Backup of All CustomerProperties and Custom Device-Properties of associated devices.
##
## v1.6 TBD
## -(issue) Get-NCCustomerList - Renew-option to rebuild cache.
## -(issue) Get-Help <CmdLet> -detailed - Not showing Parameter Helpmessage
## -UserAdd function added to Class (No CmdLet yet)
## -CustomerAdd function enhanced
## -Default CustomerID autoupdate for Hosted NCentral.
## -ShowProgress option for NCDevicePropertyList using optimized API-calls or Filters.
## -Check URL-structure before connecting.
##
##
## v2.0 TBD
## -CP -Backup/Restore to/from JSON v2
##
#Region Classes and Generic Functions
using namespace System.Net
Class NCentral_Connection {
## Using the Interface ServerEI2_PortType
## See documentation @:
## http://mothership.n-able.com/dms/javadoc_ei2/com/nable/nobj/ei2/ServerEI2_PortType.html
#Region Properties
## TODO - Enum-lists for ErrorIDs, ...
## TODO - Cleanup WebProxy code (whole module)
## Initialize the API-specific values (as static).
## No separate NameSpace needed because of Class-enclosure. Instance NameSpace available as Property.
#static hidden [String]$NWSNameSpace = "NCentral" + ([guid]::NewGuid()).ToString().Substring(25)
#static hidden [String]$SoapURL = "/dms2/services2/ServerEI2?wsdl" ## for WebserviceProxy
static hidden [String]$SoapURL = "/dms2/services2/ServerEI2" ##
## Create Properties
[String]$PSNCVersion = "1.6" ## The PS-NCentral version
[String]$ConnectionURL ## Server FQDN
[String]$BindingURL ## Full SOAP-path
hidden [PSCredential]$Creds = $null ## Encrypted Credentials
#[String]$AllProtocols = 'tls12,tls13' ## Https encryption --> issue on older systems, not supporting 1.3
[String]$AllProtocols = @(If (([System.Net.SecurityProtocolType]).DeclaredMembers.Name -contains "Tls13") { 'tls12,tls13' } Else { 'tls12' }) ## Https encryption - minimum Tls 1.2 needed
[int]$RequestTimeOut = 100 ## Default timeout in Seconds
#hidden [Object]$NameSpace ## For accessing API-Class Objects (WebServiceProxy). Deprecated from version 1.2.
#hidden [Object]$ConnectedVersion ## For storing full VersionInfoGet-data. Changed to Method 'NCVersionRequest'.
[Boolean]$IsConnected = $false ## Connection Status
[Boolean]$IsHosted = $false ## Hosted N-Central indicator (Info from NCVersionRequest)
[String]$NCVersion ## The UI-version of the connected server (Info from NCVersionRequest)
[int]$DefaultCustomerID ## Used when no CustomerID is supplied in most device-commands
[Object]$Error ## Last known Error
## Create a general Key/Value Pair. Will be casted at use. Skipped in most methods for non-reuseablity.
## Integrated (available in session only): $KeyPair = New-Object -TypeName ($NameSpace + '.tKeyPair')
#hidden $KeyPair = [PSObject]@{Key=''; Value='';}
## Create Key/Value Pairs container(Array).
hidden [Array]$KeyPairs = @()
## Defaults and ValidationLists
hidden [Array]$rc #Returned Raw Collection of NCentral-Data.
hidden [Boolean]$CustomerDataModified = $false #Customer-Cache rebuild flag
hidden [Collections.ArrayList]$RequestFilter = @() #Hold categories to Limit/Filter AssetDetails
## Validation/Lookup-lists
hidden [Collections.IDictionary]$NCStatus=@{} #Status Code/Description. Initiated/filled in the constructor.
hidden [Array]$UserValidation = @() #Supports UserAddition. Initiated/filled in the constructor.
hidden [Object]$CustomerData #Caching of CustomerData for quick reference. Filled at connect.
hidden [Array]$CustomerValidation = @() #Supports decision between Customer- and Organization-properties. Filled at connect.
## Work In Progress
#$tCreds
## Testing / Debugging only
hidden $Testvar
# $this.Testvar = $this.GetType().name
#EndRegion
#Region Constructors
#Base Constructors
## Using ConstructorHelper for chaining.
NCentral_Connection(){
Try{
## [ValidatePattern('^server\d{1,4}$')]
$ServerFQDN = Read-Host "Enter the fqdn of the N-Central Server"
}
Catch{
Write-Host "Connection Aborted"
Break
}
$PSCreds = Get-Credential -Message "Enter NCentral API-User credentials"
$this.ConstructorHelper($ServerFQDN,$PSCreds)
}
NCentral_Connection([String]$ServerFQDN){
$PSCreds = Get-Credential -Message "Enter NCentral API-User credentials"
$this.ConstructorHelper($ServerFQDN,$PSCreds)
}
NCentral_Connection([String]$ServerFQDN,[String]$JWT){
$SecJWT = (ConvertTo-SecureString $JWT -AsPlainText -Force)
$PSCreds = New-Object PSCredential ("_JWT", $SecJWT)
$this.ConstructorHelper($ServerFQDN,$PSCreds)
}
NCentral_Connection([String]$ServerFQDN,[PSCredential]$PSCreds){
$this.ConstructorHelper($ServerFQDN,$PSCreds)
}
hidden ConstructorHelper([String]$ServerFQDN,[PSCredential]$Credentials){
## Constructor Chaining not Standard in PowerShell. Needs a Helper-Method.
##
## ToDo: ValidatePattern for $ServerFQDN
If (!$ServerFQDN){
Write-Host "Invalid ServerFQDN given."
Break
}
If (!$Credentials){
Write-Host "No Credentials given."
Break
}
## Construct Session-parameters.
## Place in Class-Property for later reference.
$this.ConnectionURL = $ServerFQDN
$this.Creds = $Credentials
#Write-Debug "Connecting to $this.ConnectionURL."
## Remove prefix if given
If ($this.ConnectionURL.Contains("://")){
$this.ConnectionURL = $this.ConnectionURL.Split("://")[1]
}
$this.bindingURL = "https://" + $this.ConnectionURL + [NCentral_Connection]::SoapURL
## Remove existing/previous default-instance. Clears previous login.
If($null -ne $Global:_NCSession){
Remove-Variable _NCSession -scope global
}
## Initiate the session to the NCentral-server.
$this.Connect()
## Fill Reference/Lookup-lists
## NCStatus - correct spelling essential for ActiveIssuesList filtering.
$this.NCStatus.1 = "No Data"
$this.NCStatus.2 = "Stale"
$this.NCStatus.3 = "Normal" ## --> Nothing returned in ActiveIssuesList
$this.NCStatus.4 = "Warning"
$this.NCStatus.5 = "Failed"
$this.NCStatus.6 = "Misconfigured"
$this.NCStatus.7 = "Disconnected"
$this.NCStatus.8 = "Disabled"
$this.NCStatus.11 = "Unacknowledged"
$this.NCStatus.12 = "Acknowledged"
## Supports UserAddition
$this.UserValidation = @("customerID",
"email",
"password",
"firstname",
"lastname",
"username",
"country",
"zip/postalcode",
"street1",
"street2",
"city",
"state/province",
"telephone",
"ext",
"department",
"notificationemail",
"status",
"userroleID",
"accessgroupID",
"apionlyuser"
)
}
#EndRegion
#Region Methods
# ## Features
# ## Returns all data as Object-collections to allow pipelines.
# ## Mimic the names of the API-method where possible.
# ## Supports Synchronous Requests only (for now).
# ## NO 'Dangerous' API's are implemented (Delete/Remove).
# ##
# ## To Do
# ## TODO - Check for $this.IsConnected before execution.
# ## TODO - General Error-handling + customized throws.
# ## TODO - Additional Add/Set-methods
# ## TODO - Progress indicator (Write-Progress) - Not all commands yet
# ## TODO - Error on AccessGroupGet
# ## TODO - Async processing
# ##
#Region ClassSupport
## Connection Support
[void]Connect(){
## Reset connection-indicator
$this.IsConnected = $false
## Secure communications
[System.Net.ServicePointManager]::ServerCertificateValidationCallback = {$true} ## Seems indifferent for N-Central communication.
[System.Net.ServicePointManager]::SecurityProtocol = [System.Net.SecurityProtocolType]$this.AllProtocols
## Extract NCental UI version from returned data
$this.NCVersion = ($this.NCVersionRequest() |
Where-Object {$_.key -eq "Installation: Deployment Product Version"} ).value
## Is this hosted N-Central
$Hosted = $($this.NCVersionRequest() |
Where-Object {$_.key -eq 'N-able Hosted Platform'} ).value
If($Hosted -eq "NCOD"){
$this.IsHosted = $true
}
## TODO Make valid check on connection-error (incl. Try/Catch)
## Now checking on succesful version-data retrieval.
if ($this.NCVersion){
$this.IsConnected = $true
}
## Fill cache-settings and validation-lists.
## CustomerList-cache is filled. --> moved to Get-NCCustomerList
#$this.CustomerData = $this.customerlist()
## Store names of standard customer-properties. For differentiating from COPs.
# CustomerAdd/Modify fields put in front for template exports.
$this.CustomerValidation = @("customerid","customername","parentid") + ($this.customerlist($true) | ## only fetch SO for speed purposes
get-member |
where-object {$_.membertype -eq "noteproperty"} ).name |
Select-Object $_ -Unique
}
hidden [String]PlainUser(){
$CredUser = $this.Creds.GetNetworkCredential().UserName
If ($CredUser -eq '_JWT'){
Return $null
}
Else{
Return $CredUser
}
}
hidden [String]PlainPass(){
Return $this.Creds.GetNetworkCredential().Password
}
[void]ErrorHandler(){
$this.ErrorHandler($this.Error)
}
[void]ErrorHandler($ErrorObject){
#Write-Host$ErrorObject.Exception|Format-List -Force
#Write-Host ($ErrorObject.Exception.GetType().FullName)
# $global:ErrObj = $ErrorObject
# Write-Host ($ErrorObject.Exception.Message)
Write-Host ($ErrorObject.ErrorDetails.Message)
# Known Errors List:
# Connection-error (https): There was an error downloading ..
# 1012 - Thrown when mandatory settings are not present in "settings".
# 2001 - Required parameter is null - Thrown when null values are entered as inputs.
# 2001 - Unsupported version - Thrown when a version not specified above is entered as input.
# 2001 - Thrown when a bad username-password combination is input, or no PSA integration has been set up.
# 2100 - Thrown when invalid MSP N-central credentials are input.
# 2100 - Thrown when MSP-N-central credentials with MFA are used.
# 3010 - Maximum number of users reached.
# 3012 - Specified email address is already assigned to another user.
# 3014 - Creation of a user for the root customer (CustomerID 1) is not permitted.
# 3014 - When adding a user, must not be an LDAP user.
# 3020 - Account is locked
# 3022 - Customer/Site already exists.
# 3026 - Customer name length has exceeded 120 characters.
# 4000 - SessionID not found or has expired.
# 5000 - An unexpected exception occurred.
# 5000 - Query failed.
# 5000 - javax.validation.ValidationException: Unable to validate UI session
# 9910 - Service Organization already exists.
#
Break
}
## API Requests
hidden [Object]NCWebRequest([String]$APIMethod,[String]$APIData){
Return $this.NCWebRequest($APIMethod,$APIData,'')
}
hidden [Object]NCWebRequest([String]$APIMethod,[String]$APIData,$Version){
## Basic NCentral SOAP-request, invoking Credentials.
## Optionally invoke version (specific requests)
#version - Determines whether MSP N-Central or PSA credentials are to be used. In the case of PSA credentials the number indicates the type of PSA integration setup.
# "0.0" indicates that MSP N-central credentials are to be used.
# "1.0" indicates that a ConnectWise PSA integration is to be used.
# "2.0" indicates that an Autotask PSA integration is to be used.
# "3.0" indicates that a Tigerpaw PSA integration is to be used.
#
$VersionKey = ''
If($Version){
$VersionKey = ("
<ei2:version>{0}</ei2:version>" -f $Version)
}
## Build SoapRequest (Ending Here-String ("@) must always be left-lined.)
$MySoapRequest =(@"
<soap:Envelope xmlns:soap="http://www.w3.org/2003/05/soap-envelope" xmlns:ei2="http://ei2.nobj.nable.com/">
<soap:Header/>
<soap:Body>
<ei2:{0}>{4}
<ei2:username>{1}</ei2:username>
<ei2:password>{2}</ei2:password>{3}
</ei2:{0}>
</soap:Body>
</soap:Envelope>
"@ -f $APIMethod, $this.PlainUser(), $this.PlainPass(), $APIData, $VersionKey)
#Write-host $MySoapRequest ## Debug purposes.
#$this.Testvar = $MySoapRequest ## Debug purposes.
## Set the Request-properties in a local Dictionary / Hash-table.
$RequestProps = @{}
$RequestProps.Method = "Post"
$RequestProps.Uri = $this.BindingURL
$RequestProps.TimeoutSec = $this.RequestTimeOut
$RequestProps.body = $MySoapRequest
$FullReponse = $null
Try{
#$FullReponse = Invoke-RestMethod -Uri $this.bindingURL -body $MySoapRequest -Method POST
$FullReponse = Invoke-RestMethod @RequestProps
}
# Catch [System.Net.WebException]{
# Write-Host ([string]::Format("Error : {0}", $_.Exception.Message))
# $this.Error = $_
# $this.ErrorHandler()
# }
Catch {
Write-Host ([string]::Format("Error : {0}", $_.Exception.Message))
$this.Error = $_
$this.ErrorHandler()
}
#$ReturnProperty = $$APIMethod + "Response"
$ReturnClass = $FullReponse.envelope.body | Get-Member -MemberType Property
$ReturnProperty = $ReturnClass[0].Name
Return $FullReponse.envelope.body.$ReturnProperty.return
}
hidden [Object]NCVersionRequest(){
$Version = $null
## Use versionInfoGet, Includes checking SOAP-connection
## No credentials needed (yet).
$APIMethod = "versionInfoGet"
$VersionEnvelope = (@"
<soap:Envelope xmlns:soap="http://www.w3.org/2003/05/soap-envelope" xmlns:ei2="http://ei2.nobj.nable.com/">
<soap:Header/>
<soap:Body>
<ei2:{0}/>
</soap:Body>
</soap:Envelope>
"@ -f $APIMethod) ## End of Here-String must be left-lined.
## Set the Request-properties in a local Dictionary / Hash-table.
$RequestProps = @{}
$RequestProps.Method = "Post"
$RequestProps.Uri = $this.BindingURL
$RequestProps.TimeoutSec = $this.RequestTimeOut
$RequestProps.body = $VersionEnvelope
Try{
$Version = (Invoke-RestMethod @RequestProps).envelope.body.($APIMethod + "Response").return |
Select-Object key,value
## Additional connection-info available using Invoke-WebRequest
#$this.Testvar = Invoke-WebRequest @RequestProps
#Write-Host ("Security Protocols Used = {0} " -f [Net.ServicePointManager]::SecurityProtocol)
## Same Version info using WebRequest iso RestMethod
#$Version = ([XML](Invoke-WebRequest @RequestProps).Content).envelope.body.($APIMethod + "Response").return |
# Select-Object key,value
}
# Catch [System.Net.WebException]{
# $this.Error = $_
# $this.ErrorHandler()
# }
Catch {
$this.Error = $_
$this.ErrorHandler()
}
Return $Version
}
hidden [Object]GetNCData([String]$APIMethod,[String]$Username,[String]$PassOrJWT,$KeyPairs){
## Overload for Backward compatibility only
Return $this.GetNCData($APIMethod,$KeyPairs,'')
}
hidden [Object]GetNCData([String]$APIMethod,[Array]$KeyPairs){
Return $this.GetNCData($APIMethod,$KeyPairs,'')
}
hidden [Object]GetNCData([String]$APIMethod,[Array]$KeyPairs,[String]$Version){
## Process Keys to Request-settings
$MyKeys=""
If ($KeyPairs){
ForEach($KeyPair in $KeyPairs){
## KeyValue can be an array with multiple values
$MyValues=""
ForEach($KeyValue in $KeyPair.value){
$MyValues = $MyValues + ("
<ei2:value>{0}</ei2:value>" -f $KeyValue)
}
$MyKeys = $MyKeys + ("
<ei2:settings>
<ei2:key>{0}</ei2:key>{1}
</ei2:settings>" -f $KeyPair.Key, $MyValues)
}
}
## Invoke request
Return $this.NCWebRequest($APIMethod, $MyKeys,$Version)
}
hidden [Object]GetNCDataOP([String]$APIMethod,[Array]$CustomerIDs,[Boolean]$ReverseOrder){
## Get OrganizationProperties for (optional) specified customerIDs
## Process Array
$MyKeys=""
ForEach($CustomerID in $CustomerIDs){
$MyKeys += ("
<ei2:customerIds>{0}</ei2:customerIds>" -f $CustomerID)
}
## Add mandatory options
$MyKeys += ("
<ei2:reverseOrder>{0}</ei2:reverseOrder>" -f ($ReverseOrder.ToString()).ToLower())
## Invoke request
Return $this.NCWebRequest($APIMethod, $MyKeys)
}
hidden [Object]GetNCDataDP([String]$APIMethod,[Array]$DeviceIDs,[Array]$DeviceNames,[Array]$FilterIDs,[Array]$FilterNames,[Boolean]$ReverseOrder){
## Get DeviceProperties for (optional) filtered devices
## Process Arrays
$MyKeys=""
If($DeviceIDs){
ForEach($DeviceID in $DeviceIDs){
$MyKeys += ("
<ei2:deviceIDs>{0}</ei2:deviceIDs>" -f $DeviceID)
}
}
If($DeviceNames){
ForEach($DeviceName in $DeviceNames){
$MyKeys += ("
<ei2:deviceNames>{0}</ei2:deviceNames>" -f $DeviceName)
}
}
If($FilterIDs){
ForEach($FilterID in $FilterIDs){
$MyKeys += ("
<ei2:filterIDs>{0}</ei2:filterIDs>" -f $FilterID)
}
}
If($FilterNames){
ForEach($FilterName in $FilterNames){
$MyKeys += ("
<ei2:filterNames>{0}</ei2:filterNames>" -f $FilterName)
}
}
$MyKeys += ("
<ei2:reverseOrder>{0}</ei2:reverseOrder>" -f ($ReverseOrder.ToString()).ToLower())
## Invoke request
Return $this.NCWebRequest($APIMethod, $MyKeys)
}
hidden [Object]SetNCDataOP([String]$APIMethod,$OrganizationID,$OrganizationPropertyID,[String]$OrganizationPropertyValue){
## Set a single OrganizationProperty
## Process Arrays
$MyKeys=("
<ei2:organizationProperties>
<ei2:customerId>{0}</ei2:customerId>
<ei2:properties>
<ei2:propertyId>{1}</ei2:propertyId>
<ei2:value>{2}</ei2:value>
</ei2:properties>
</ei2:organizationProperties>" -f $OrganizationID,$OrganizationPropertyID,$OrganizationPropertyValue)
## Invoke request
Return $this.NCWebRequest($APIMethod, $MyKeys)
}
hidden [Object]SetNCDataDP([String]$APIMethod,$DeviceID,$DevicePropertyID,[String]$DevicePropertyValue){
## Set a single DeviceProperty
## Process Arrays
$MyKeys=("
<ei2:deviceProperties>
<ei2:deviceID>{0}</ei2:deviceID>
<ei2:properties>
<ei2:devicePropertyID>{1}</ei2:devicePropertyID>
<ei2:value>{2}</ei2:value>
</ei2:properties>
</ei2:deviceProperties>" -f $DeviceID, $DevicePropertyID, $DevicePropertyValue)
## Invoke request
Return $this.NCWebRequest($APIMethod, $MyKeys)
}
## Data Management / Processing
hidden[PSObject]ProcessData1([Array]$InArray){
Return $this.ProcessData1($InArray,$false)
}
<#
hidden[PSObject]ProcessData1([Array]$InArray,[String]$PairClass){
Return $this.ProcessData1($InArray,$PairClass,$false)
}
#>
hidden[PSObject]ProcessData1([Array]$InArray,[Boolean]$ShowProgress){
## Most Common PairClass is Info or Item.
## Fill if not specified.
# Hard (Pre-)Fill / Default
$PairClass = "info"
## Base on found Array-Properties if possible
If($InArray.Count -gt 0){
## Only one property exists at this level. The name of this property specifies the DeviceClass.
#$PairClass = ($InArray[0] | Get-member -MemberType Property).Name
$PairClass = ($InArray[0] | Get-member -MemberType Property)[0].Name
}
Return $this.ProcessData1($InArray,$PairClass,$ShowProgress)
}
hidden[PSObject]ProcessData1([Array]$InArray,[String]$PairClass,[Boolean]$ShowProgress){
## Received Dataset KeyPairs 2 List/Columns
$OutObjects = @()
if ($InArray){
$TotalObjects=$InArray.Count ## For progress-indicator
$CurrentObject = 0
## Process all items
[System.Collections.ArrayList]$AllColumns = @() ## To fix issue with different # of object-properties.
foreach ($InObject in $InArray) {
If($ShowProgress){
$CurrentObject +=1
#Write-host ("Processing {0} of {1} devices." -f $CurrentObject, $TotalObjects)
$CompletedPercent = ($CurrentObject / $TotalObjects)*100
Write-Progress -Activity ("Processing {0} Objects."-f $TotalObjects) -Status ("{0:N1}% Complete:" -f $CompletedPercent) -PercentComplete $CompletedPercent
#Start-Sleep -Milliseconds 250
}
# $ThisObject = New-Object PSObject ## In this routine the object is created at start. Properties are added with values.
$Props = @{} ## In this routine the object is created at the end. Properties from a list/Hashtable.
## Add a Reference-Column at Object-Level (for Custom Properties)
If ($PairClass -eq "Properties"){
## Add reference to customer or device from the top-level.
## CustomerLink if Available
if(Get-Member -inputobject $InObject -name "CustomerID"){
# $ThisObject | Add-Member -MemberType NoteProperty -Name 'CustomerID' -Value $InObject.CustomerID -Force
$Props.CustomerID = $InObject.CustomerID
$AllColumns += 'CustomerID'
}
## DeviceLink if Available
if(Get-Member -inputobject $InObject -name "DeviceID"){
# $ThisObject | Add-Member -MemberType NoteProperty -Name 'DeviceID' -Value $InObject.DeviceID -Force
$Props.DeviceID = $InObject.DeviceID
$AllColumns += 'DeviceID'
}
}
## Convert all (remaining) keypairs to Properties
## issue here with Pairclass 'Properties' when properties-column is empty (only possible with devices/CDPs) --> Foreach is skipped
foreach ($item in $InObject.$PairClass) {
## Cleanup the Key (Header) and/or Value before usage.
If ($PairClass -eq "Properties"){
$Header = $item.label
}
Else{
If($item.key.split(".")[0] -eq 'asset'){ ##Should use ProcessData2 (ToDo)
$Header = $item.key
}
Else{
$Header = $item.key.split(".")[1]
}
}
## Fill the array of all Unique headers for output (FixProperties).
#$AllColumns += $Header --> Disabled for speed-effect. Use 'Fixproperties' after return instead.
# Only unique HeaderNames allowed
#$AllColumns = $AllColumns | Sort-Object -Unique --> Breaks the module.
## Ensure a Flat/String Value of multiple entries for now --> work to do?
If ($item.value -is [Array]){
#$DataValue = $item.Value[0]
$DataValue = $item.Value -join ","
}
Else{
$DataValue = $item.Value
}
## Now add the Key/Value pairs. (When using the 'pre-defined Object' option. )
# $ThisObject | Add-Member -MemberType NoteProperty -Name $Header -Value $DataValue -Force
# if a key is found that already exists in the hashtable
if ($Props.ContainsKey($Header)) {
# either overwrite the value 'Last-One-Wins'
# or do nothing 'First-One-Wins'
#if ($this.allowOverwrite) { $Props[$Header] = $DataValue }
}
else {
#$Props[$Header] = $DataValue
#$Props.add($Header,$DataValue)
$Props.$Header = $DataValue
}
}
$ThisObject = New-Object -TypeName PSObject -Property $Props #Alternative option - create object from hash-table
## Add the Object to the list
## !! Only Properties of the first object seem used for return !! --> If objects with no properties at all are included.
$OutObjects += $ThisObject
}
<#
## Attempt to fix 'Properties from first object only' issue.
## breaks $outobjects now
If($AllColumns){
## Unify all Object-properties
#$AllColumns = $AllColumns | Sort-Object -Unique
## Deal with long-names containing spaces. (Custom Properties mainly)
[String]$ColumnString = $AllColumns -join ","
$OutObjects = $OutObjects | Select-Object $ColumnString.split(",")
}
#>
## Convert Date-fields of root-object
$OutObjects = $this.FixDates($OutObjects)
If($ShowProgress){
#Write-Progress -Activity ("Processed {0} Objects."-f $OutObjects.count) -Status "Ready"
#Start-Sleep -Milliseconds 1000
Write-Progress -Activity ("Processed {0} Objects."-f $OutObjects.count) -Status "Ready" -Completed
}
}
## Return the list of Objects
Return $OutObjects
#Return $this.FixProperties($OutObjects)
}
hidden[PSObject]ProcessData2([Array]$InArray){
Return $this.ProcessData2($InArray,$false)
}
hidden[PSObject]ProcessData2([Array]$InArray,[Boolean]$ShowProgress){
## Most Common PairClass is Info or Item.
## Fill if not specified.
# Hard (Pre-)Fill
$PairClass = "info"
## Base on found Array-Properties if possible
If($InArray.Count -gt 0){
$PairClasses = $InArray[0] | Get-member -MemberType Property
$PairClass = $PairClasses[0].Name
}
Return $this.ProcessData2($InArray,$PairClass,$ShowProgress)
}
hidden[PSObject]ProcessData2([Array]$InArray,[String]$PairClass,[Boolean]$ShowProgress){
## Convert Received Dataset KeyPairs to a multi-level Object
## Key-structure: asset.service.caption.28
## service - Property or Sub-object
## caption - key
## ## - Service-item (sub-identifier)
##
## Each Asset in dataset is processed sepearately and added to the output.
## Output-List
$OutObjects = @()
## Inputcheck - is there any data to process?
If ($InArray){
$TotalObjects=$InArray.Count
$CurrentObject = 0
## Process all devices
ForEach ($Object in $InArray){
If($ShowProgress){
$CurrentObject +=1
#Write-host ("Processing {0} of {1} devices." -f $CurrentObject, $TotalObjects)
$CompletedPercent = ($CurrentObject / $TotalObjects)*100
Write-Progress -Activity ("Processing {0} Objects."-f $TotalObjects) -Status ("{0:N1}% Complete:" -f $CompletedPercent) -PercentComplete $CompletedPercent
#Start-Sleep -Milliseconds 250
}
## Get the DeviceId to repeat in every Object/Array-Property
$CurrentDeviceID = ($Object.$PairClass | Where-Object {$_.key -eq 'asset.device.deviceid'}).value
#Write-Debug "DeviceObject CurrentDeviceID: $CurrentDeviceID"
## Sort keys for before processing. Column 2 and 4
$SortedInfo = $Object.$PairClass | Sort-Object @{Expression={$_.key.split(".")[1] + $_.key.split(".")[3]}; Descending=$false}
## Init
$Props = @{} ## In this routine the object is created at the end. Properties from this list.
## For processing properties and additional identifiers (column4)
$OldArrayID = ""
[Array]$ArrayProperty = $null
$OldArrayItemID = ""
[HashTable]$ArrayItemProperty = $null
## Convert the key/value-pairs to a Multi-Layer Object with Properties
ForEach ($KeyPair in $SortedInfo) {
## Key-structure: asset.service.caption.28
## Outer-loop differenting on column 2 MainObject Array-Property
## Inner-loop differenting on column 4
## ObjectItem is column 2.4 (easysplit) Array-ItemID
## ObjectHeaders are Column 3 Array-Item-PropertyHeader
## ObjectValue = Value
## Treat 'device' as Root
## Add Sub-objects for all other headers
## Add deviceid to each sub-object for easy reference
## Add property direct to sub-object if column4 (index) does not exist
## Build and Add an Array-property to sub-object if column4 is an int
$KeySplit = $KeyPair.key.split(".")
$KeyValue = $KeyPair.value
If(($KeySplit[1]) -eq 'device'){
## Add device-properties to the root as a Non-Array.
$Header = $KeySplit[2]
## Ensure a Flat (character-separated) Value for now --> work to do?
If ($KeyValue -is [Array]){
$Props.$Header = $KeyValue -join ","
}
Else{
$Props.$Header = $KeyValue
}
}
Else{
## Add property as an (Array of) Object(s).
## Make an object-Array Before Adding to root
## Create the unique Property ItemID from the Key-Name
If($KeySplit[3]){
## Property has index-column
$ArrayItemId = ("{0}.{1}" -f $KeySplit[1], $KeySplit[3])
}
Else{
## No index-column
$ArrayItemId = $KeySplit[1]
}
## Is this a new Array-Item?
If($ArrayItemId -ne $OldArrayItemID){
## Add the current object to the array-property and start over
If($OldArrayItemID -ne ""){
$ArrayItem = New-Object -TypeName PSObject -Property $ArrayItemProperty
$ArrayProperty += $ArrayItem
}
## (Re-)Init
$ArrayItemProperty = @{}
$OldArrayItemID = $ArrayItemId
## Add an unique ID-Column and the DeviceID to the item.
$ArrayItemProperty.ItemId=$ArrayItemId
$ArrayItemProperty.DeviceId=$CurrentDeviceID
}
## Create the Main Property Name from the Key-Name
$ArrayId = $KeySplit[1]
## Is this a new Array?
If($ArrayId -ne $OldArrayID){
## Add the current array to the main object and start a new one
If($OldArrayID -ne ""){
#Write-Debug "ArrayId = $ArrayId"
$Props.$OldArrayId = $ArrayProperty
}
## (Re-)Init
$ArrayProperty = $null
$OldArrayID = $ArrayId
}
## Add the current item to the array-item
$Header2 = $KeySplit[2]
$ArrayItemProperty.$Header2=$KeyValue
}
## End of Keypairs-loop
}
## Build object for last ArrayItem too
If($ArrayItemProperty){
$ArrayItem = New-Object -TypeName PSObject -Property $ArrayItemProperty
$ArrayProperty += $ArrayItem
}
## Add the last build array to the main Object
If($ArrayProperty){
$Props.$OldArrayId = $ArrayProperty
}
## Create the Multi-layer Object, using the generated properties.
$ThisObject = New-Object -TypeName PSObject -Property $Props
## Add the Multi-layer Object to the Output-list
$OutObjects += $ThisObject
## End of Objects-loop - Get Next
}
## Convert all Date-fields of root-object from string to date
$OutObjects = $this.FixDates($OutObjects)
If($ShowProgress){
Write-Progress -Activity ("Processed {0} Objects."-f $OutObjects.count) -Status "Ready" -Completed
#Start-Sleep -Milliseconds 250
}
## End of Input-check / process data
}
## Return the list of Objects
Return $OutObjects
}
[PSObject]IsEncodedBase64([string]$InputString){
## UniCode by default
Return $this.IsEncodedBase64($InputString,$false)
}
[PSObject]IsEncodedBase64([string]$InputString,[Boolean]$UTF8){
#[OutputType([Boolean])]
$DataIsEncoded = $true
Try{
## Try Decode
If($UTF8){
[System.Text.Encoding]::UTF8.GetString([System.Convert]::FromBase64String($InputString)) | Out-Null
}
Else{
[System.Text.Encoding]::Unicode.GetString([System.Convert]::FromBase64String($InputString)) | Out-Null
}
}
Catch{
## Data was not encoded yet
$DataIsEncoded = $false
}
Return $DataIsEncoded
}
[PSObject]ConvertBase64([String]$Data){
## Encode and Unicode as default
Return $this.ConvertBase64($Data,$false,$false)
}
[PSObject]ConvertBase64([String]$Data,[Bool]$Decode){
## Unicode as default
Return $this.ConvertBase64($Data,$Decode,$false)
}
[PSObject]ConvertBase64([String]$Data,[Bool]$Decode,[Bool]$UTF8){
## Init
[string]$ReturnData = $Data
$DataIsEncrypted = $true
If($Data){
## Test content to avoid double-encoding.
## Still needs some work for false positives. Now checks for valid code-length mainly.
## Encoded without Byte Order Mark (BOM). Makes recognition difficult.
Try{
## Try Decode
If($UTF8){
$ReturnData = [System.Text.Encoding]::UTF8.GetString([System.Convert]::FromBase64String($Data))
}
Else{
$ReturnData = [System.Text.Encoding]::Unicode.GetString([System.Convert]::FromBase64String($Data))
}
}
Catch{
## Data was not valid encoded yet
$DataIsEncrypted = $false
}
## If data should not be decrypted.
If (!$Decode){
If ($DataIsEncrypted){
## Return Already Encrypted Data
$ReturnData = $Data
}
Else{
## Return Newly Encrypted Data