-
Notifications
You must be signed in to change notification settings - Fork 4
/
New-CosmosDocument.ps1
86 lines (74 loc) · 2.94 KB
/
New-CosmosDocument.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
function New-CosmosDocument {
<#
.SYNOPSIS
Creates a new Cosmos Document
.DESCRIPTION
Creates a new Cosmos Document in the Collection you specify
.PARAMETER DatabaseName
Name of the Database containing the Collection where the document should be created
.PARAMETER CollectionName
Name of the Collection where the Document should be created
.PARAMETER Document
A hashtable containing your document. Remember the id key. The cmdlet converts the hashtable to json
.PARAMETER CosmosDBVariables
This is the Script variable generated by Connect-CosmosDB - no need to supply this variable, unless you get really creative
.EXAMPLE
$Document = @{
id='91387b17-2f3b-4a2d-bb6f-d4b9362990f0'
GivenName='Utter'
Surname='Despair'}
New-CosmosDocument -DatabaseName MyPrivateCosmos -CollectionName Chaos -Document $Document
.NOTES
https://docs.microsoft.com/en-us/rest/api/documentdb/create-a-document
#>
[CmdletBinding()]
param (
[Parameter(Mandatory=$true,
HelpMessage='Name of the Database containing the Collection')]
[string]$DatabaseName,
[Parameter(Mandatory=$true,
HelpMessage='Name of the Collection where the Document should be created')]
[string]$CollectionName,
[Parameter(Mandatory=$true,
HelpMessage='The document formatted as a hashtable')]
[hashtable]$Document,
[Parameter(Mandatory=$false,
HelpMessage="Use Connect-CosmosDB to create this Variable collection")]
[hashtable]$CosmosDBVariables=$Script:CosmosDBVariables
)
begin {
Test-CosmosDBVariable $CosmosDBVariables
$Database = $CosmosDBConnection[($DatabaseName + '_db')]
if (-not $Database) {
Write-Warning "$DatabaseName not found"
continue
}
$Collection = $CosmosDBConnection[$DatabaseName][$CollectionName]
if (-not $Collection) {
Write-Warning "Collection $CollectionName Database $DatabaseName not found"
continue
}
if (!$Document['id']){
Write-Warning "There is no id value in the document"
continue
}
}
process {
$Verb = 'POST'
$Url = '{0}/{1}docs' -f $CosmosDBVariables['URI'],$Collection._self
$ResourceType = 'docs'
$Header = New-CosmosDBHeader -resourceId $Collection._rid -resourceType $ResourceType -Verb $Verb
$Header['x-ms-documentdb-is-upsert'] = 'true'
$CosmosBody = $Document | ConvertTo-Json
Write-Verbose $CosmosBody
try {
$Return = Invoke-RestMethod -Uri $Url -Headers $Header -Method $Verb -Body $CosmosBody -ErrorAction Stop
Write-Verbose "$($Document['id']) has been created in $CollectionName"
}
catch {
Write-Warning -Message $_.Exception.Message
}
}
end {
}
}