Команде powershell не найдено исключение -Метод - PullRequest
0 голосов
/ 04 февраля 2020

При использовании следующего в powershell оно копируется с веб-сайта для обработки онлайн-платежей через приложение. Я изменяю маркер доступа и уникальный ключ при написании этого.

$authHeader = @{ Authorization = 'Bearer  {0}' -f "{{ACCESS_TOKEN}}" }
$body = '{
   "idempotency_key": "{{UNIQUE-KEY}}",
   "autocomplete": true,
   "amount_money": {
     "amount": 100,
     "currency": "USD"
   },
   "source_id": "cnon:card-nonce-ok"
   }
}'

Invoke-RestMethod -Uri https://connect.squareupsandbox.com/v2/payments |
  -Method Post |
  -ContentType "application/json" |
  -Headers $authHeader |
  -Body $body 

я получаю следующее исключение

-Method : The term '-Method' is not recognized as the name of a cmdlet, function, script file, or operable program.
 Check the spelling of the name, or if a path was included, verify that the path is correct and try again.
  At line:14 char:4   
     +    -Method Post |                                      
 +    ~~~~~~~                                                                                                               
 + CategoryInfo          : ObjectNotFound: (-Method:String) [], CommandNotFoundException                                
 + FullyQualifiedErrorId : CommandNotFoundException   

или если я удалю их | и вместо этого используйте пробел, как сказано в комментарии:

$authHeader = @{ Authorization = 'Bearer  {0}' -f "{{ACCESS_TOKEN}}" }
$body = '{
   "idempotency_key": "{{UNIQUE-KEY}}",
   "autocomplete": true,
   "amount_money": {
     "amount": 100,
     "currency": "USD"
   },
   "source_id": "cnon:card-nonce-ok"
   }
}'

Invoke-RestMethod -Uri https://connect.squareupsandbox.com/v2/payments 
  -Method Post 
  -ContentType "application/json" 
  -Headers $authHeader 
  -Body $body 

я получаю следующее исключение, и, как показано, старое исключение -Method все еще существует.

Invoke-RestMethod : {"errors": [{"code": "UNAUTHORIZED","detail": "Your request did not include an `Authorization`
http header with an access token. The header value is expected to be of the format \"Bearer TOKEN\"  (without
quotation marks), where TOKEN is to be replaced with your access token  (e.g. \"Bearer {{Access token}}\"). For
more information, see https://docs.connect.squareup.com/api/connect/v2/#requestandresponseheaders. If you are seeing
this error message while using one of our officially supported client libraries, please report this to
developers@squareup.com. ","category": "AUTHENTICATION_ERROR"}]}
At line:13 char:1
+ Invoke-RestMethod -Uri https://connect.squareupsandbox.com/v2/payment ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (System.Net.HttpWebRequest:HttpWebRequest) [Invoke-RestMethod], WebExc
   eption
    + FullyQualifiedErrorId : WebCmdletWebResponseException,Microsoft.PowerShell.Commands.InvokeRestMethodCommand
-Method : The term '-Method' is not recognized as the name of a cmdlet, function, script file, or operable program.
Check the spelling of the name, or if a path was included, verify that the path is correct and try again.
At line:14 char:4
+    -Method Post
+    ~~~~~~~
    + CategoryInfo          : ObjectNotFound: (-Method:String) [], CommandNotFoundException
    + FullyQualifiedErrorId : CommandNotFoundException

-ContentType : The term '-ContentType' is not recognized as the name of a cmdlet, function, script file, or operable
program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again.
At line:15 char:4
+    -ContentType "application/json"
+    ~~~~~~~~~~~~
    + CategoryInfo          : ObjectNotFound: (-ContentType:String) [], CommandNotFoundException
    + FullyQualifiedErrorId : CommandNotFoundException

-Headers : The term '-Headers' is not recognized as the name of a cmdlet, function, script file, or operable program.
Check the spelling of the name, or if a path was included, verify that the path is correct and try again.
At line:16 char:4
+    -Headers $authHeader
+    ~~~~~~~~
    + CategoryInfo          : ObjectNotFound: (-Headers:String) [], CommandNotFoundException
    + FullyQualifiedErrorId : CommandNotFoundException

-Body : The term '-Body' is not recognized as the name of a cmdlet, function, script file, or operable program. Check
the spelling of the name, or if a path was included, verify that the path is correct and try again.
At line:17 char:4
+    -Body $body
+    ~~~~~
    + CategoryInfo          : ObjectNotFound: (-Body:String) [], CommandNotFoundException
    + FullyQualifiedErrorId : CommandNotFoundException

1 Ответ

2 голосов
/ 04 февраля 2020

Хотя канал | можно использовать для разбиения строки на несколько строк, этот оператор применяется только для серии команд, использующих конвейер.

Параметры, связанные с командой, не могут быть разделенным конвейером, как это.

У вас есть 3 варианта.

Поместите все параметры в одну строку, разделив их пробелами, например:

Invoke-RestMethod -Uri https://connect.squareupsandbox.com/v2/payments -Method Post -ContentType "application/json" -Headers $authHeader -Body $body

Используйте Splatting и определите ваши параметры в хеш-таблице затем примените их к команде, используя @, чтобы указать, что вы передаете список параметров и этих значений, а не просто один хеш-таблицу.

$params = @{
    ContentType = "application/json"
    Method = 'Post'
    Body = $body
    Headers = $authHeader
    Uri = 'https://connect.squareupsandbox.com/v2/payments'
}
Invoke-RestMethod @params 

Используйте символ обратного удара `.

Invoke-RestMethod -Uri https://connect.squareupsandbox.com/v2/payments `
    -Method Post `
    -ContentType "application/json" `
    -Headers $authHeader `
    -Body $body 
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...