ElasticSearch Query with Powershell Invoke-RestMethod

Hi-
I have a Elastic Search Rest API to query along with range condition, which would need to be executed thru Powershell using Invoke-RestMethod command, but it fails. It works alright using Curl.

Curl command:

curl -u User:Password -X GET "localhost:9200/test_data-*/_count" -H 'Content-Type: application/json' -d'
{
"query": {
"range" : {
"@timestamp" : {
"gte" : "now-15m/m",
"lte" : "now"
}
}
}
}
'

I have written the below powershell script:

$response = Invoke-RestMethod "http://localhost:9200/test_data-*/_count" -Method Get -Headers @{Authorization=("Basic {0}" -f $authHeaderValue)}
-Body "{
"query": {
"range" : {
"@timestamp" : {
"gte" : "now-15m/m",
"lte" : "now"
}
}
}
}"

I get this error:

Invoke-RestMethod : Cannot send a content-body with this verb-type.
At line:1 char:13

Could someone help me how do I make a GET request with body block in Powershell? Thanks !

Use POST instead.

PowerShell doesn't support a GET request with a body, so you need to use POST instead as @dadoonet suggests.

If you need to work with Elasticsearch frequently with PowerShell, you may be interested in using Elastic.Console, a small PowerShell module that provides cmdlets for

  1. executing requests
  2. API path autocompletion
  3. ability to convert from and execute Kibana Console examples.
1 Like

Sure @forloop. I'd use the console going forward. I find it very useful. Thanks !

@dadoonet - POST call worked, am able to get the same output as GET calls. I hope the POST method doesn't make any impact to the data we already collected ? thanks !

It won't. Elasticsearch supports POST for APIs that accept GET with a request body for languages that don't support GET with a request body.

Great, and thanks for confirming @forloop :slight_smile:

1 Like

This topic was automatically closed 28 days after the last reply. New replies are no longer allowed.