-
Notifications
You must be signed in to change notification settings - Fork 19
/
Copy pathCWManage.psm1
4764 lines (4020 loc) · 144 KB
/
CWManage.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
#region [Helpers]-------
function Connect-CWM {
<#
.SYNOPSIS
This will initialize the authorization variable.
.DESCRIPTION
This will create a global variable that contains all needed connection and authorization information.
All other commands from the module will call this variable to get connection information.
.PARAMETER Server
The URL of your ConnectWise Mange server.
Example: manage.mydomain.com
.PARAMETER Company
The login company.
.PARAMETER clientId
Integration Identifier created by a user. See https://developer.connectwise.com/ClientID
.PARAMETER pubkey
Public API key created by a user
docs: My Account
.PARAMETER privatekey
Private API key created by a user
docs: My Account
.PARAMETER Credentials
Manage username and password as a PSCredential object [pscredential].
.PARAMETER IntegratorUser
The integrator username
docs: Member Impersonation
.PARAMETER IntegratorPass
The integrator password
docs: Member Impersonation
.PARAMETER MemberID
The member that you are impersonating
.PARAMETER Force
Ignore cached information and recreate
.PARAMETER DontWarn
Used to suppress the warning about integrator accounts.
.EXAMPLE
$Connection = @{
Server = $Server
Company = $Company
pubkey = $pubkey
privatekey = $privatekey
clientId = $clientId
}
Connect-CWM @Connection
.EXAMPLE
$Connection = @{
Server = $Server
Company = $Company
IntegratorUser = $IntegratorUser
IntegratorPass = $IntegratorPass
clientId = $clientId
}
Connect-CWM @Connection
.EXAMPLE
$Connection = @{
Server = $Server
Company = $Company
IntegratorUser = $IntegratorUser
IntegratorPass = $IntegratorPass
MemberID = $MemberID
clientId = $clientId
}
Connect-CWM @Connection
.EXAMPLE
$Connection = @{
Server = $Server
Company = $Company
Credentials = $Credentials
clientId = $clientId
}
Connect-CWM @Connection
.NOTES
Author: Chris Taylor
Date: 10/10/2018
Author: Darren White
Update Date: 8/8/2019
Purpose/Change: Added support for clientId header
.LINK
http://labtechconsulting.com
https://developer.connectwise.com/Manage/Developer_Guide#Authentication
#>
[CmdletBinding()]
param(
[Parameter(Mandatory=$true)]
[string]$Server,
[Parameter(Mandatory=$true)]
[string]$Company,
[string]$pubkey,
[string]$privatekey,
[string]$clientId,
[pscredential]$Credentials,
[string]$IntegratorUser,
[string]$IntegratorPass,
[string]$MemberID,
[switch]$Force,
[switch]$DontWarn
)
# Version supported
$Version = '3.0.0'
if ((($global:CWMServerConnection -and !$global:CWMServerConnection.expiration) -or $global:CWMServerConnection.expiration -gt $(Get-Date)) -and !$Force) {
Write-Verbose "Using cached Authentication information."
return
}
# Validate server
$Server = ($Server -replace("http.*:\/\/",'') -split '/')[0]
# API key
if($pubkey -and $privatekey){
Write-Verbose "Using API Key authentication"
$Authstring = "$($Company)+$($pubkey):$($privatekey)"
$encodedAuth = [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes($Authstring));
$Headers = @{
Authorization = "Basic $encodedAuth"
clientId = $clientId
'Cache-Control'= 'no-cache'
}
}
# Cookies, yumy
elseif($Credentials){
Write-Verbose "Using Cookie authentication"
$global:CWMServerConnection = @{}
$Headers = @{ clientId = $clientId }
$Body = @{
CompanyName = $Company
UserName = $Credentials.UserName
Password = $Credentials.GetNetworkCredential().Password
}
$URI = "https://$($Server)/v4_6_release//login/login.aspx?response=json"
$WebRequestArguments = @{
Uri = $Uri
Method = 'Post'
Body = $Body
SessionVariable = 'global:CWMSession'
}
# Create session variable. Cookies are stored in that object
$null = Invoke-CWMWebRequest -Arguments $WebRequestArguments
}
# Integrator account w/ w/o member id
elseif($IntegratorUser -and $IntegratorPass){
Write-Verbose "Using Integrator authentication"
if(!$DontWarn){
Write-Warning "Please move to a different authentication method."
Write-Warning "Use the -DontWarn switch to suppress this message."
Write-Warning "https://developer.connectwise.com/Products/Manage/Developer_Guide#Authentication"
}
$Authstring = $Company + '+' + $IntegratorUser + ':' + $IntegratorPass
$encodedAuth = [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes($Authstring))
$Headers = @{
Authorization = "Basic $encodedAuth"
clientId = $clientId
'x-CW-usertype' = "integrator"
'Cache-Control'= 'no-cache'
}
if ($MemberID) {
Write-Verbose "Impersonating user, $MemberID"
$URL = "https://$($Server)/v4_6_release/apis/3.0/system/members/$($MemberID)/tokens"
$Body = @{
memberIdentifier = $MemberID
}
$URI = "https://$($Server)/v4_6_release//login/login.aspx?response=json"
$WebRequestArguments = @{
Method = 'Post'
Uri = $URL
Body = $Body
ContentType = 'application/json'
}
$Result = Invoke-CWMWebRequest -Arguments $WebRequestArguments
if($Result.content){
$Result = $Result.content | ConvertFrom-Json
}
else {
Write-Error "Issue getting Auth Token for impersonated user, $MemberID"
return
}
# Create auth header for Impersonated user
$expiration = [datetime]$Result.expiration
$Authstring = $Company + '+' + $Result.publicKey + ':' + $Result.privateKey
$encodedAuth = [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes(($Authstring)));
$Headers = @{
Authorization = "Basic $encodedAuth"
clientId = $clientId
'Cache-Control'= 'no-cache'
}
}
}
# not enough info
else {
Write-Error "Valid authentication parameters not passed"
return
}
# Create the Server Connection object
$global:CWMServerConnection = @{
Server = $Server
Headers = $Headers
Session = $CWMSession
expiration = $expiration
}
# Set version header info
$global:CWMServerConnection.Headers.Accept = "application/vnd.connectwise.com+json; version=$Version"
# Validate connection info
Write-Verbose 'Validating authentication'
$Info = Get-CWMSystemInfo
if(!$Info) {
Write-Warning 'Authentication failed. Clearing connection settings.'
Disconnect-CWM
return
}
$global:CWMServerConnection.Version = $Info.version
Write-Verbose 'Connection successful.'
Write-Verbose '$CWMServerConnection, variable initialized.'
}
function Disconnect-CWM {
<#
.SYNOPSIS
This will remove the ConnectWise Manage authorization variable.
.EXAMPLE
Disconnect-CWM
.NOTES
Author: Chris Taylor
Date: 10/10/2018
.LINK
http://labtechconsulting.com
#>
[CmdletBinding()]
param()
$null = Remove-Variable -Name CWMServerConnection -Scope global -Force -Confirm:$false -ErrorAction SilentlyContinue
if($CWMServerConnection -or $global:CWMServerConnection) {
Write-Error "There was an error clearing connection information.`n$($Error[0])"
} else {
Write-Verbose '$CWMServerConnection, variable removed.'
}
}
function ConvertTo-CWMTime {
<#
.SYNOPSIS
Converts [datetime] to the time format used in condition queries.
.DESCRIPTION
This will convert an input to a universal date time object then output in a format used by the ConnectWise Manage API.
.PARAMETER Date
Date used in conversion.
.PARAMETER RawTime
Outputs time without braces
.EXAMPLE
ConvertTo-CWMTime $(Get-Date).AddDays(1)
Will output tomorrows date.
.NOTES
Author: Chris Taylor
Date: 10/16/2018
.LINK
http://labtechconsulting.com
#>
param(
[Parameter(ValueFromPipeline = $true)]
[datetime]$Date,
[switch]$Raw
)
$Converted = "[$(Get-Date $Date.ToUniversalTime() -format yyyy-MM-ddTHH:mm:ssZ)]"
if($Raw){
$Converted = $Converted.Trim('[]')
}
return $Converted
}
function ConvertFrom-CWMTime {
<#
.SYNOPSIS
Converts ConnectWise Manage datetime string to a [datetime] object.
.DESCRIPTION
This will convert an input string to [datetime] object.
.PARAMETER Date
Date used in conversion.
.OUTPUT
[datetime]
.EXAMPLE
ConvertFrom-CWMTime -Date '[2018-10-20T00:14:56Z]'
Will return a [datetime] conversion of datetime string.
.NOTES
Author: Chris Taylor
Date: 10/16/2018
.LINK
http://labtechconsulting.com
#>
param(
[string]$Date
)
return Get-Date $Date.Trim('[',']')
}
function ConvertFrom-CWMColumnRow {
<#
.SYNOPSIS
Take Column Row output from Manage and converts it to an object
.PARAMETER Data
Column row object to be converted
.EXAMPLE
ConvertFrom-CWMColumnRow -Data $Data
.NOTES
Author: Chris Taylor
Date: 10/10/2018
.LINK
http://labtechconsulting.com
#>
param(
$Data
)
$dataTable = New-Object System.Data.DataTable
$Data.column_definitions | ForEach-Object {
if (!$dataTable.Columns.Contains($($_ | Get-Member | Where-Object {$_.membertype -eq 'noteproperty'}).Name)){
$dataTable.Columns.Add(($_ | Get-Member | Where-Object {$_.membertype -eq 'noteproperty'}).Name)
}
} | Out-Null
$Data.row_values | ForEach-Object {
$dataTable.rows.Add($_)
} | Out-Null
if($dataTable){Return $dataTable}
Return $False
}
function Invoke-CWMGetMaster {
<#
.SYNOPSIS
This will be basis of all get calls to the ConnectWise Manage API.
.DESCRIPTION
This will insure that all GET requests are handled correctly.
.PARAMETER Arguments
A hash table of parameters
.PARAMETER URI
The URI of the GET endpoint
.EXAMPLE
Invoke-CWMGetMaster -Arguments $Arguments -URI $URI
.NOTES
Author: Chris Taylor
Date: 10/10/2018
.LINK
http://labtechconsulting.com
https://developer.connectwise.com/Manage/Developer_Guide#Authentication
#>
[CmdletBinding()]
param (
$Arguments,
[string]$URI
)
if ($Arguments.Condition) {
$Condition = [System.Web.HttpUtility]::UrlEncode($Arguments.Condition)
$URI += "?conditions=$Condition"
}
if($Arguments.childconditions) {
$childconditions = [System.Web.HttpUtility]::UrlEncode($Arguments.childconditions)
$URI += "&childconditions=$childconditions"
}
if($Arguments.customfieldconditions) {
$customfieldconditions = [System.Web.HttpUtility]::UrlEncode($Arguments.customfieldconditions)
$URI += "&customfieldconditions=$customfieldconditions"
}
if($Arguments.orderBy) {$URI += "&orderBy=$($Arguments.orderBy)"}
$WebRequestArguments = @{
Uri = $URI
Method = 'GET'
}
if ($Arguments.all) {
$Result = Invoke-CWMAllResult -Arguments $WebRequestArguments
}
else {
if($Arguments.pageSize){$WebRequestArguments.URI += "&pageSize=$pageSize"}
if($Arguments.page){$WebRequestArguments.URI += "&page=$page"}
$Result = Invoke-CWMWebRequest -Arguments $WebRequestArguments
if($Result.content){
try{
$Result = $Result.content | ConvertFrom-Json
}
catch{}
}
}
return $Result
}
function Invoke-CWMSearchMaster {
<#
.SYNOPSIS
This will be basis of all search calls to the ConnectWise Manage API.
.DESCRIPTION
This will insure that all search requests are handled correctly.
.PARAMETER Arguments
A hash table of parameters
.PARAMETER URI
The URI of the search endpoint
.EXAMPLE
Invoke-CWMSearchMaster -Arguments $Arguments -URI $URI
.NOTES
Author: Chris Taylor
Date: 10/10/2018
.LINK
http://labtechconsulting.com
https://developer.connectwise.com/Manage/Developer_Guide#Authentication
#>
[CmdletBinding()]
param (
$Arguments,
[string]$URI
)
$Body = @{}
switch ($Arguments.Keys) {
'condition' { $Body.conditions = $Arguments.condition }
'orderBy' { $Body.orderBy = $Arguments.orderBy }
'childconditions' { $Body.childconditions = $Arguments.childconditions }
'customfieldconditions' { $Body.customfieldconditions = $Arguments.customfieldconditions }
}
$Body = ConvertTo-Json $Body -Depth 100
Write-Verbose $Body
$WebRequestArguments = @{
Uri = $URI
Method = 'Post'
ContentType = 'application/json'
Body = $Body
Headers = $Global:CWMServerConnection.Headers
}
if ($Arguments.all) {
$Result = Invoke-CWMAllResult -Arguments $WebRequestArguments
}
else {
if($Arguments.pageSize){$WebRequestArguments.URI += "&pageSize=$pageSize"}
if($Arguments.page){$WebRequestArguments.URI += "&page=$page"}
$Result = Invoke-CWMWebRequest -Arguments $WebRequestArguments
if($Result.content){
$Result = $Result.content | ConvertFrom-Json
}
}
return $Result
}
function Invoke-CWMDeleteMaster {
<#
.SYNOPSIS
This will be basis of all delete calls to the ConnectWise Manage API.
.DESCRIPTION
This will insure that all delete requests are handled correctly.
.PARAMETER Arguments
A hash table of parameters
.PARAMETER URI
The URI of the delete endpoint
.EXAMPLE
Invoke-CWMDeleteMaster -Arguments $Arguments -URI $URI
.NOTES
Author: Chris Taylor
Date: 10/10/2018
.LINK
http://labtechconsulting.com
#>
[CmdletBinding()]
param (
$Arguments,
[string]$URI
)
$WebRequestArguments = @{
Uri = $URI
Method = 'Delete'
}
$Result = Invoke-CWMWebRequest -Arguments $WebRequestArguments
# Error if status not 204
# if($Result.StatusCode -ne 204) {
# Write-Error "There was an error with the delete $($Result.StatusCode)"
# }
# if($Result.content){
# $Result = $Result.content | ConvertFrom-Json
# }
# return $Result
}
function Invoke-CWMPatchMaster {
<#
.SYNOPSIS
This will be basis of all Patch calls to the ConnectWise Manage API.
.DESCRIPTION
This will insure that all update requests are handled correctly.
.PARAMETER Arguments
A hash table of parameters
.PARAMETER URI
The URI of the update endpoint
.EXAMPLE
Invoke-CWMPatchMaster -Arguments $Arguments -URI $URI
.NOTES
Author: Chris Taylor
Date: 10/10/2018
.LINK
http://labtechconsulting.com
#>
[CmdletBinding()]
param (
$Arguments,
[string]$URI
)
Write-Verbose $($Arguments.Value | Out-String)
$global:TArguments = $Arguments
$Body =@(
@{
op = $Arguments.Operation
path = $Arguments.Path
value = $Arguments.Value
}
)
$Body = ConvertTo-Json $Body -Depth 100
Write-Verbose $Body
$WebRequestArguments = @{
Uri = $URI
Method = 'Patch'
ContentType = 'application/json'
Body = $Body
}
$Result = Invoke-CWMWebRequest -Arguments $WebRequestArguments
if($Result.content){
$Result = $Result.content | ConvertFrom-Json
}
return $Result
}
function Invoke-CWMNewMaster {
<#
.SYNOPSIS
This will be basis of all create calls to the ConnectWise Manage API.
.DESCRIPTION
This will insure that all create requests are handled correctly.
.PARAMETER Arguments
A hash table of parameters
.PARAMETER URI
The URI of the create endpoint
.EXAMPLE
Invoke-CWMPatchMaster -Arguments $Arguments -URI $URI
.NOTES
Author: Chris Taylor
Date: 10/10/2018
.LINK
http://labtechconsulting.com
#>
[CmdletBinding()]
param (
$Arguments,
[string]$URI,
[string[]]$Skip
)
# Skip common parameters
$Skip += 'Debug','ErrorAction','ErrorVariable','InformationAction','InformationVariable','OutVariable','OutBuffer','PipelineVariable','Verbose','WarningAction','WarningVariable','WhatIf','Confirm','ErrorAction','Verbose'
$Body = @{}
foreach($i in $Arguments.GetEnumerator()){
if($Skip -notcontains $i.Key){
$Body.Add($i.Key, $i.value)
}
}
$Body = ConvertTo-Json $Body -Depth 100
Write-Verbose $Body
$WebRequestArguments = @{
Uri = $URI
Method = 'Post'
ContentType = 'application/json'
Body = $Body
}
$Result = Invoke-CWMWebRequest -Arguments $WebRequestArguments
if($Result.content){
$Result = $Result.content | ConvertFrom-Json
}
return $Result
}
function Invoke-CWMAllResult {
<#
.SYNOPSIS
This will handel web requests for all results to the ConnectWise Manage API.
.DESCRIPTION
This will enable forward only pagination and loop all results.
.PARAMETER Arguments
A hash table of parameters
.EXAMPLE
Invoke-CWMAllResult -Arguments $Arguments
.NOTES
Author: Chris Taylor
Date: 10/10/2018
.LINK
http://labtechconsulting.com
#>
[CmdletBinding()]
param(
$Arguments
)
# Update header for new pagination-type
$Arguments.Headers += @{
'pagination-type' = 'forward-only'
}
# Up the pagesize to max
$Arguments.URI += "&pageSize=999"
# First request
$PageResult = Invoke-CWMWebRequest -Arguments $Arguments
if(!$PageResult){return}
if(!$PageResult.Headers.ContainsKey('Link')){
Write-Error "The $((Get-PSCallStack)[2].Command) Endpoint doesn't support 'forward-only' pagination. Please report to ConnectWise."
return
}
$NextPage = $PageResult.Headers.Link.Split(';')[0].trimstart('<').trimend('>')
$Collection = @()
$Collection += $PageResult.Content | ConvertFrom-Json
# Loop through all results
while ($NextPage) {
$Arguments.Uri = $NextPage
$PageResult = Invoke-CWMWebRequest -Arguments $Arguments
if (!$PageResult){return}
$Collection += $PageResult.Content | ConvertFrom-Json
$NextPage = $PageResult.Headers.Link.Split(';')[0].trimstart('<').trimend('>')
}
return $Collection
}
function Invoke-CWMWebRequest {
<#
.SYNOPSIS
This function is used to handle all web requests to the ConnectWise Manage API.
.DESCRIPTION
This function is used to manage error handling with web requests.
It will also handle retries of failed attempts.
.PARAMETER Arguments
A splat object of web request parameters
.PARAMETER MaxRetry
The maximum number of retry attempts
.NOTES
Author: Chris Taylor
Date: 10/10/2018
.LINK
http://labtechconsulting.com
#>
[CmdletBinding()]
param(
$Arguments,
[int]$MaxRetry = 5
)
# Check that we have cached connection info
if(!$global:CWMServerConnection){
$ErrorMessage = @()
$ErrorMessage += "Not connected to a Manage server."
$ErrorMessage += $_.ScriptStackTrace
$ErrorMessage += ''
$ErrorMessage += '--> $CWMServerConnection variable not found.'
$ErrorMessage += "----> Run 'Connect-CWM' to initialize the connection before issuing other CWM commandlets."
Write-Error ($ErrorMessage | Out-String)
return
}
# Add default set of arguments
foreach($Key in $Global:CWMServerConnection.Headers.Keys){
if($Arguments.Headers.Keys -notcontains $Key){
$Arguments.Headers += @{$Key = $Global:CWMServerConnection.Headers.$Key}
}
}
if(!$Arguments.SessionVariable){ $Arguments.WebSession = $global:CWMServerConnection.Session }
# Check URI format
if($Arguments.URI -notlike '*`?*' -and $Arguments.URI -like '*`&*') {
$Arguments.URI = $Arguments.URI -replace '(.*?)&(.*)', '$1?$2'
}
# Issue request
try {
$Result = Invoke-WebRequest @Arguments -UseBasicParsing
}
catch {
if($_.Exception.Response){
# Read exception response
$ErrorStream = $_.Exception.Response.GetResponseStream()
$Reader = New-Object System.IO.StreamReader($ErrorStream)
$global:ErrBody = $Reader.ReadToEnd() | ConvertFrom-Json
# Start error message
$ErrorMessage = @()
if($errBody.code){
$ErrorMessage += "An exception has been thrown."
$ErrorMessage += $_.ScriptStackTrace
$ErrorMessage += ''
$ErrorMessage += "--> $($ErrBody.code)"
if($errBody.code -eq 'Unauthorized'){
$ErrorMessage += "-----> $($ErrBody.message)"
$ErrorMessage += "-----> Use 'Disconnect-CWM' or 'Connect-CWM -Force' to set new authentication."
}
else {
$ErrorMessage += "-----> $($ErrBody.message)"
$ErrorMessage += "-----> ^ Error has not been documented please report. ^"
}
}
}
if ($_.ErrorDetails) {
$ErrorMessage += "An error has been thrown."
$ErrorMessage += $_.ScriptStackTrace
$ErrorMessage += ''
$global:errDetails = $_.ErrorDetails | ConvertFrom-Json
$ErrorMessage += "--> $($errDetails.code)"
$ErrorMessage += "--> $($errDetails.message)"
if($errDetails.errors.message){
$ErrorMessage += "-----> $($errDetails.errors.message)"
}
}
Write-Error ($ErrorMessage | out-string)
return
}
# Not sure this will be hit with current iwr error handling
# May need to move to catch block need to find test
# TODO Find test for retry
# Retry the request
$Retry = 0
while ($Retry -lt $MaxRetry -and $Result.StatusCode -eq 500) {
$Retry++
# ConnectWise Manage recommended wait time
$Wait = $([math]::pow( 2, $Retry))
Write-Warning "Issue with request, status: $($Result.StatusCode) $($Result.StatusDescription)"
Write-Warning "$($Retry)/$($MaxRetry) retries, waiting $($Wait)ms."
Start-Sleep -Milliseconds $Wait
$Result = Invoke-WebRequest @Arguments -UseBasicParsing
}
if ($Retry -ge $MaxRetry) {
Write-Error "Max retries hit. Status: $($Result.StatusCode) $($Result.StatusDescription)"
return
}
return $Result
}
#endregion [Helpers]-------
#region [Company]-------
#region [Companies]-------
function Get-CWMCompany {
<#
.SYNOPSIS
This function will list companies based on conditions.
.PARAMETER Condition
This is your search condition to return the results you desire.
Example:
(contact/name like "Fred%" and closedFlag = false) and dateEntered > [2015-12-23T05:53:27Z] or summary contains "test" AND summary != "Some Summary"
.PARAMETER orderBy
Choose which field to sort the results by
.PARAMETER childconditions
Allows searching arrays on endpoints that list childConditions under parameters
.PARAMETER customfieldconditions
Allows searching custom fields when customFieldConditions is listed in the parameters
.PARAMETER page
Used in pagination to cycle through results
.PARAMETER pageSize
Number of results returned per page (Defaults to 25)
.PARAMETER all
Return all results
.EXAMPLE
Get-CWMCompany -Condition "status/id IN (1,42,43,57)" -all
Will return all companies that match the condition
.NOTES
Author: Chris Taylor
Date: 10/10/2018
.LINK
http://labtechconsulting.com
https://developer.connectwise.com/manage/rest?a=Company&e=Companies&o=GET
#>
[CmdletBinding()]
param(
[string]$Condition,
[ValidateSet('asc','desc')]
$orderBy,
[string]$childconditions,
[string]$customfieldconditions,
[int]$page,
[int]$pageSize,
[switch]$all
)
$URI = "https://$($global:CWMServerConnection.Server)/v4_6_release/apis/3.0/company/companies"
return Invoke-CWMGetMaster -Arguments $PsBoundParameters -URI $URI
}
function Update-CWMCompany {
<#
.SYNOPSIS
This will update a company.
.PARAMETER CompanyID
The ID of the company that you are updating. Get-CWMCompanies
.PARAMETER Operation
What you are doing with the value.
replace, add, remove
.PARAMETER Path
The value that you want to perform the operation on.
.PARAMETER Value
The value of path.
.EXAMPLE
$UpdateParam = @{
CompanyID = $Company.id
Operation = 'replace'
Path = 'name'
Value = $NewName
}
Update-CWMCompany @UpdateParam
.NOTES
Author: Chris Taylor
Date: 10/10/2018
.LINK
http://labtechconsulting.com
https://developer.connectwise.com/products/manage/rest?a=Company&e=Companies&o=UPDATE
#>
[CmdletBinding()]
param(
[Parameter(Mandatory=$true)]
$CompanyID,
[Parameter(Mandatory=$true)]
[validateset('add','replace','remove')]
$Operation,
[Parameter(Mandatory=$true)]
[string]$Path,
[Parameter(Mandatory=$true)]
[string]$Value
)
$URI = "https://$($global:CWMServerConnection.Server)/v4_6_release/apis/3.0/company/companies/$CompanyID"
return Invoke-CWMPatchMaster -Arguments $PsBoundParameters -URI $URI
}
#endregion [Companies]-------
#region [CompanyNoteTypes]-------
function Get-CWMCompanyNoteTypes {
<#
.SYNOPSIS
This function will list company note types based on conditions.
.PARAMETER Condition
This is your search condition to return the results you desire.
Example:
(contact/name like "Fred%" and closedFlag = false) and dateEntered > [2015-12-23T05:53:27Z] or summary contains "test" AND summary != "Some Summary"
.PARAMETER orderBy
Choose which field to sort the results by
.PARAMETER childconditions
Allows searching arrays on endpoints that list childConditions under parameters
.PARAMETER customfieldconditions
Allows searching custom fields when customFieldConditions is listed in the parameters
.PARAMETER page
Used in pagination to cycle through results
.PARAMETER pageSize
Number of results returned per page (Defaults to 25)
.PARAMETER all
Return all results
.EXAMPLE
Get-CWMCompanyNoteTypes -Condition "status/id IN (1,42,43,57)" -all
Will return all company notes that match the condition
.NOTES
Author: Chris Taylor
Date: <GET-DATE>
.LINK
http://labtechconsulting.com
https://developer.connectwise.com/products/manage/rest?a=Company&e=CompanyNoteTypes&o=GET
#>
[CmdletBinding()]
param(
[string]$Condition,
[ValidateSet('asc','desc')]
$orderBy,
[string]$childconditions,
[string]$customfieldconditions,
[int]$page,
[int]$pageSize,
[switch]$all
)
$URI = "https://$($global:CWMServerConnection.Server)/v4_6_release/apis/3.0/company/noteTypes"
return Invoke-CWMGetMaster -Arguments $PsBoundParameters -URI $URI
}
#endregion [CompanyNoteTypes]-------
#region [CompanyNotes]-------
function Get-CWMCompanyNotes {
<#
.SYNOPSIS
This function will list company notes based on conditions.
.PARAMETER CompanyID
The ID of the company you need to retrieve notes from.
.PARAMETER Condition
This is your search condition to return the results you desire.
Example: