无法使用 powershell rest API 从 Cosmos 中获取文档数

库马尔

尝试使用 Powershell 使用 Rest API https://docs.microsoft.com/en-us/rest/api/cosmos-db/query-documents查询 Cosmos我收到以下错误

Invoke-RestMethod :远程服务器返回错误:(400) 错误请求

Function Generate-MasterKeyAuthorizationSignature{
    [CmdletBinding()]
    Param(
        [Parameter(Mandatory=$true)][String]$verb,
        [Parameter(Mandatory=$true)][String]$resourceLink,
        [Parameter(Mandatory=$true)][String]$resourceType,
        [Parameter(Mandatory=$true)][String]$dateTime,
        [Parameter(Mandatory=$true)][String]$key,
        [Parameter(Mandatory=$true)][String]$keyType,
        [Parameter(Mandatory=$true)][String]$tokenVersion
    )
    $hmacSha256 = New-Object System.Security.Cryptography.HMACSHA256
    $hmacSha256.Key = [System.Convert]::FromBase64String($key)

    If ($resourceLink -eq $resourceType) {
        $resourceLink = ""
    }

    $payLoad = "$($verb.ToLowerInvariant())`n$($resourceType.ToLowerInvariant())`n$resourceLink`n$($dateTime.ToLowerInvariant())`n`n"
    $hashPayLoad = $hmacSha256.ComputeHash([System.Text.Encoding]::UTF8.GetBytes($payLoad))
    $signature = [System.Convert]::ToBase64String($hashPayLoad)

[System.Web.HttpUtility]::UrlEncode("type=$keyType&ver=$tokenVersion&sig=$signature")
}

Function Query-CosmosDocuments{
    [CmdletBinding()]
    Param(
        [Parameter(Mandatory=$true)][String]$EndPoint,
        [Parameter(Mandatory=$true)][String]$DBName,
        [Parameter(Mandatory=$true)][String]$CollectionName,
        [Parameter(Mandatory=$true)][String]$MasterKey,
        [Parameter(Mandatory=$false)][String]$JSON,      
        [String]$Verb="POST"
    )
    $ResourceType = "docs";
    $ResourceLink = "dbs/$DBName/colls/$CollectionName"
$query=@"
{  
  "query": "SELECT VALUE COUNT(1) FROM c",  
  "parameters": [  ]  
} 
"@

#$query= "SELECT VALUE COUNT(1) FROM c"

    $dateTime = [DateTime]::UtcNow.ToString("r")
    $authHeader = Generate-MasterKeyAuthorizationSignature -verb $Verb -resourceLink $ResourceLink -resourceType $ResourceType -key $MasterKey -keyType "master" -tokenVersion "1.0" -dateTime $dateTime
    $header = @{authorization=$authHeader;"x-ms-version"="2017-02-22";"x-ms-documentdb-isquery"="True";"x-ms-date"=$dateTime}
    $contentType= "application/query+json"
    $queryUri = "$EndPoint$ResourceLink/docs"
    #$header
    #$queryUri

    [Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
    $result = Invoke-RestMethod -Method $Verb -ContentType $contentType -Uri $queryUri -Headers $header -Body $query 
    return $result
}

Add-Type -AssemblyName System.Web
$CosmosDBEndPoint = "https://Mydev.documents.azure.com:443/"
$DBName = "MyDev"
$CollectionName = "ArchiveSummary"
$MasterKey = "MyMasterKey"

Query-CosmosDocuments -EndPoint $CosmosDBEndPoint -DBName $DBName -CollectionName $CollectionName -MasterKey $MasterKey

Cosmos 创建脚本

$resourceGroupName='mytestcosmos'
$accountName='testcosmosaccount' 
az group create -l westus -n $resourceGroupName
az cosmosdb create --name $accountName --resource-group $resourceGroupName 


$databaseName='database1'

az cosmosdb database create -n $accountName -g $resourceGroupName -d $databaseName --throughput 1000

$collectionName = 'collection1'
$partitionKey = '/name'

az cosmosdb collection create -g $resourceGroupName -n $accountName -d $databaseName -c $collectionName --partition-key-path $partitionKey
Jim Xu

根据我的测试,如果想用PowerShell调用Azure Cosmos DB rest api,请参考以下脚本

$Key="<your master key>"
$Verb="POST"
$ResourceType="docs"
$ResourceLink ="dbs/ToDoList/colls/Items"
$Date= (Get-Date).ToUniversalTime().toString('R')
$KeyType="master"
$TokenVersion="1.0"

# create Authorization header
$StringToSign=$Verb.ToLowerInvariant()+"`n" +$ResourceType.ToLowerInvariant() +"`n" +$ResourceLink + "`n" +$Date.ToLowerInvariant() + "`n" + "" + "`n";
$hmacsha = New-Object System.Security.Cryptography.HMACSHA256
$hmacsha.key = [Convert]::FromBase64String($Key)
$signature = $hmacsha.ComputeHash([Text.Encoding]::UTF8.GetBytes($StringToSign))
$signature = [Convert]::ToBase64String($signature)

$authorization = [System.Web.HttpUtility]::UrlEncode("type=${KeyType}&ver=${TokenVersion}&sig=$signature")

#call rest api
$query=@"
{  
  "query": "SELECT * FROM c",  
  "parameters": [  ]  
} 
"@

$header = @{Authorization=$authorization;"x-ms-version"="2017-02-22";"x-ms-documentdb-isquery"="True";"x-ms-date"=$Date}
$contentType= "application/query+json"
$CosmosDBEndPoint="https://stancosmosdb.documents.azure.com/"
$url=$CosmosDBEndPoint+$ResourceLink+"/docs"
Invoke-RestMethod -Method $Verb -ContentType $contentType -Uri $url -Headers $header -Body $query 

欲知更多详情,请参阅

https://docs.microsoft.com/en-us/rest/api/cosmos-db/access-control-on-cosmosdb-resources

https://docs.microsoft.com/en-us/rest/api/cosmos-db/query-documents

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

使用 PowerShell (SQL API) 在 Cosmos DB 中插入文档

无法使用通过 Rest API 内置 React Native 的移动应用程序访问 Cosmos DB

使用从SharePoint文档库中获取的REST API筛选数据

PowerShell - 使用 Exchange Server 2016 REST API 获取日历事件

使用REST API Powershell在TFS 2015中添加/删除用户

使用Powershell调用Rest API-CosmosDb

通过REST API的Cosmos DB IN子句

使用Cosmos Db Mongo API的TTL按文档

无法使用PowerShell POST Cosmos DB存储过程

无法使用DocuSign REST API上传WORD文档

无法使用POST REST API更新Couchbase文档

如何使用Azure DevOps Rest API使用Powershell获取版本状态(成功,失败)

如何使用Mongo API从Cosmos DB获取收藏集名称

Cosmos DB:如何使用DocumentDB API引用单独集合中的文档

ReactJS应用无法使用REST API调用获取数据

无法使用getJSON从Flask Rest API获取Json

无法使用REST API获取查找字段值

使用 AngularJS 无法通过 REST API 获取参数

通过在Powershell脚本中使用Rest API Post方法无法停止WebJobs-获取错误403-此Web应用程序已停止

REST API 获取特定文档

Cosmos API中的过期证书

如何在PowerShell中使用REST API在TFS中创建错误?

使用PowerShell使用未签名的证书查询REST API

在 PowerShell 中检查 Cosmos DB 帐户的状态

使用无法在Cosmos中使用的数组内容搜索文档

使用Powershell从JIRA Rest API解析问题密钥

通过 PowerShell 使用 REST API 创建 JIRA 问题

使用Powershell发行jira rest-api附加文件

使用PowerShell在TFS 2015 REST API中进行队列构建