LoginSignup
11
6

More than 1 year has passed since last update.

Powershell で Curl を実行する際は引数が少し違う

Last updated at Posted at 2021-03-22

2021-11-04 追記

curl.exe を叩けば Shellscript ライクな引数でも実行できるとコメントで教えて頂いたので試してみました。Powershell ではエラーになってしまいますが、コマンドプロンプトでは 以下のコマンドで実行できました!

"C:\windows\System32\curl.exe" ^
    http://localhost/auth -X POST ^
        -H "Content-Type: application/json" ^
        -d "{ 'user': 'user1', 'pw': 'abcxyz' }"

curl を Powershell 上でそのまま打ったら失敗した

フレームワークのチュートリアルに、以下のような curl を打てと書かれていた。

curl http://localhost/auth -X POST \
                           -H "Content-Type: application/json" \ 
                           -d "{ 'user': 'user1', 'pw': 'abcxyz' }"

最近の PowerShell は ls とかが普通に使えるので、curl も行けるかと思いコピペして実行したら以下の通りエラーとなった。

Invoke-WebRequest : パラメーター 'Headers' をバインドできません。
"Content-Type: application/json" の値を "System.String" 型から
"System.Collections.IDictionary" 型に変換できません。
発生場所 行:1 文字:44
... (省略) ...

引数が Linux の curl とは完全一致していないようで、先述のコードは以下の通り書いたら動いた。

Invoke-RestMethod -Uri "http://localhost:5000/auth" -Method POST `
                  -Body (@{"user"="user1";"pw"="abcxyz"} | ConvertTo-Json) `
                  -ContentType "application/json"

ヘッダーを送信したい場合、以下のように書いたら動いた。

$headers = @{}
$headers["Authorization"] = "JWT aaa.bbb.ccc"
$headers["X-AAA"] = "AAA"
$headers["X-BBB"] = "BBB"
Invoke-RestMethod -Uri "http://localhost:5000/protected" -Headers $headers
11
6
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
11
6