forked from KelvinTegelaar/AutotaskAPI
-
Notifications
You must be signed in to change notification settings - Fork 0
/
New-AutotaskAPIResource.ps1
68 lines (64 loc) · 2.59 KB
/
New-AutotaskAPIResource.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
<#
.SYNOPSIS
Creates a new resource in the API to the supplied object.
.DESCRIPTION
Creates resource in the API to the supplied object. Uses the Post method. Null values will not be published.
.EXAMPLE
PS C:\> New-AutotaskAPIResource -resource companies -body $body
Creates a new company using the body $body
.INPUTS
-Resource: Which resource to find. Tab completion is available.
-Body: Body created based on the model of the API. Accepts pipeline input.
.OUTPUTS
none
.NOTES
So the API actually contains a method to get the fields for a body. Thinking of using that instead.
/atservicesrest/v1.0/EntityName/entityInformation/field
#>
function New-AutotaskAPIResource {
[CmdletBinding()]
Param(
[Parameter(Mandatory = $true, ValueFromPipeline = $true)]$Body,
[Parameter(Mandatory = $false)][String]$ParentId
)
DynamicParam {
$Script:POSTParameter
}
begin {
if (!$Script:AutotaskAuthHeader -or !$Script:AutotaskBaseURI) {
Write-Warning "You must first run Add-AutotaskAPIAuth before calling any other cmdlets"
break
}
$resource = $PSBoundParameters.resource
$headers = $Script:AutotaskAuthHeader
$ResourceURL = (($Script:Queries | Where-Object { $_.'Post' -eq $Resource }).Name | Select-Object -first 1) -replace '/query', '' | Select-Object -first 1
}
process {
if ($resource -like "*child*" ) {
if ( !$ParentId ) {
Write-Warning "You must specify a parentId when creating a child resource"
break
}
$ResourceURL = $resourceURL -replace '{parentId}', $ParentId
}
$SendingBody = $body | ConvertTo-Json -Depth 10
$body = [System.Text.Encoding]::UTF8.GetBytes($SendingBody)
try {
Invoke-RestMethod -Uri "$($Script:AutotaskBaseURI)/$($resourceurl)" -headers $Headers -Method post -Body $body
}
catch {
if ($psversiontable.psversion.major -lt 6) {
$streamReader = [System.IO.StreamReader]::new($_.Exception.Response.GetResponseStream())
$streamReader.BaseStream.Position = 0
if ($streamReader.ReadToEnd() -like '*{*') { $ErrResp = $streamReader.ReadToEnd() | ConvertFrom-Json }
$streamReader.Close()
}
if ($ErrResp.errors) {
write-error "API Error: $($ErrResp.errors)"
}
else {
write-error "Connecting to the Autotask API failed. $($_.Exception.Message)"
}
}
}
}