# Передача переменной в запросе из Powershell в Elasticsearch

**URL:** <https://discuss.elastic.co/t/powershell-elasticsearch/201395>\
**Category:** Вопросы на русском языке\
**Created:** [September 27, 2019, 12:36pm UTC](https://discuss.elastic.co/t/powershell-elasticsearch/201395 "2019-09-27T12:36:11Z")\
**Posts on this page:** 4\
**Page:** 1

<div class="post-metadata">

**Author:** ![KOTOXJle6](https://sea2.discourse-cdn.com/elastic/user_avatar/discuss.elastic.co/kotoxjle6/32/131136_2.png) [@KOTOXJle6](https://discuss.elastic.co/u/KOTOXJle6)\
**Post date:** [September 27, 2019, 12:36pm UTC](https://discuss.elastic.co/t/powershell-elasticsearch/201395/1 "2019-09-27T12:36:11Z")

</div>

Добрый день.

Хочу настроить возможность получать данные из ES через powershell. В моем случае это поиск по логу Exchange. Вижу это так: администратор запускает скрипт, вводит в переменные отправителя, получателя, дату и тему и получает результат в более-менее красивом формате. Скрипт у меня получился такой

```
$sender=Read-Host "Enter sender address"
#$recipient=Read-Host "Enter recipient address"
#$subject=Read-Host "Enter subject"

$json_body = '{
   "query": {
     "bool": {
            "must": [
         {
           "range": {
             "@timestamp": {
               "gte": "now-1d/d",
               "lte": "now/d"
             }
           }
         }
       ], 
       "should": [
         {
           "match": {
             "sender-address": "`"$sender`""
           }
         },
         {
           "match": {
           "recipient-address": "*"
           }
         },
         {
           "match_phrase": {
             "message-subject": "*"
           }
         }
       ]
     }
   }
}'

$result= Invoke-RestMethod -URI 'http://1.1.5.5:9200/exchange-*/_search?pretty' -Method 'POST' -ContentType 'application/json' -Body $json_body

$result.hits.hits._source | fl message-subject, sender-address, recipient-address, '@timestamp', source-context, event-id

```

Без использования переменных всё круто, но с переменными получаю такую ошибку:

```
Invoke-RestMethod : { "error" : { "root_cause" : [ { "type" : "json_parse_exception", "reason" : "Unexpected character ('$' (code 36)): was expecting comma to separate Object entries\n at 
[Source: org.elasticsearch.transport.netty4.ByteBufStreamInput@4345e084; line: 17, column: 36]" } ], "type" : "json_parse_exception", "reason" : "Unexpected character ('$' (code 36)): was 
expecting comma to separate Object entries\n at [Source: org.elasticsearch.transport.netty4.ByteBufStreamInput@4345e084; line: 17, column: 36]" }, "status" : 500 }
At line:39 char:10
+ $result= Invoke-RestMethod -URI 'http://1.1.5.5:9200/exchange-*/_search?pret ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo : InvalidOperation: (System.Net.HttpWebRequest:HttpWebRequest) [Invoke-RestMethod], WebException
    + FullyQualifiedErrorId : WebCmdletWebResponseException,Microsoft.PowerShell.Commands.InvokeRestMethodCommand

```

Вообще возможно передавать переменные в таких запросах?

---

<div class="post-metadata">

**Author:** ![Igor\_Motov](https://sea2.discourse-cdn.com/elastic/user_avatar/discuss.elastic.co/igor_motov/32/45193_2.png) [@Igor\_Motov](https://discuss.elastic.co/u/Igor_Motov)\
**Post date:** [September 27, 2019, 1:21pm UTC](https://discuss.elastic.co/t/powershell-elasticsearch/201395/2 "2019-09-27T13:21:27Z")

</div>

Самая важная часть в этой ошибке это:

```auto
Unexpected character ('$' (code 36)): .... line: 17, column: 36 

```

Если посмотреть на запрос, то в строке 17 видим:

```auto
       "sender-address": "`"$sender`""

```

Другими словами `$sender` не заменятся а посылается как есть. Я powershell-ом не пользуюсь, но судя по всему это должно выглядить как-то так:

```auto
       "sender-address": "'+$sender+'"

```

---

<div class="post-metadata">

**Author:** ![KOTOXJle6](https://sea2.discourse-cdn.com/elastic/user_avatar/discuss.elastic.co/kotoxjle6/32/131136_2.png) [@KOTOXJle6](https://discuss.elastic.co/u/KOTOXJle6)\
**Post date:** [September 27, 2019, 3:09pm UTC](https://discuss.elastic.co/t/powershell-elasticsearch/201395/3 "2019-09-27T15:09:22Z")

</div>

Спасибо! Я все переставлял " и ', а оказывается нужно было ставить +. Теперь все передается как надо.

---

<div class="post-metadata">

**Author:** ![system](https://us1.discourse-cdn.com/elastic/original/3X/1/a/1ac57faf039f6b580b3f104ef42a2a89e41014de.png) [@system](https://discuss.elastic.co/u/system)\
**Post date:** [October 25, 2019, 3:16pm UTC](https://discuss.elastic.co/t/powershell-elasticsearch/201395/4 "2019-10-25T15:16:20Z")

</div>

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