2017-02-23 1 views
1

저는이 두 가지 (작동하는) 컬 명령을 powershell로 변환하려고합니다. Invoke-WebRequest를 사용하여 쿠키를 어떻게 저장합니까?Powershell이 ​​인증을 위해 쿠키를 사용합니다.

세션 쿠키 강타 받기

curl -k \ 
--cookie-jar cookie \ 
-H 'Content-Type: application/json' \ 
-d '{"jsonrpc": "2.0", "id": 1, "method": "login", "params": {"username": "bob", "password": "correct-horse-battery-staple"}}' \ 
https://foo.example.com/api/session 

가져 세션 쿠키 PowerShell을

$data = @{} 
$data.jsonrpc = '2.0' 
$data.id = '1' 
$data.method = 'login' 
$data.params = @{} 
$data.params.username = 'bob' 
$data.params.password = 'correct-horse-battery-staple' 
$url = "https://foo.example.com/api/session" 
$webrequest = Invoke-WebRequest -Method POST ` 
-ContentType 'application/json' ` 
-Body $data ` 
-Uri $url ` 
-SessionVariable websession ` 
-UseBasicParsing 
$cookies = $websession.Cookies.GetCookies($url) 
Write-Host "$($cookies[0].name) = $($cookies[0].value)" 

가져 오기 버전 강타

curl -k \ 
--cookie cookie \ 
-H 'Content-Type: application/json' \ 
-d '{"jsonrpc": "2.0", "id": 2, "method": "version"}' \ 
https://foo.example.com/api/about 

가져 오기 버전 PowerShell을

$data = @{} 
$data.jsonrpc = '2.0' 
$data.id = '2' 
$data.method = 'version' 
$url = "https://foo.example.com/api/about" 
Invoke-WebRequest -Method POST ` 
-ContentType 'application/json' ` 
-Body $data ` 
-Uri $url ` 
-WebSession $websession ` 
-UseBasicParsing 
,363,210

두 번째 명령은 제대로 쿠키를 전달하고

StatusCode  : 200 
StatusDescription : OK 
Content   : {"error":{"code":-32000,"message":"Decoding failed: Syntax error","data":null},"id":null} 
RawContent  : HTTP/1.1 200 OK 
        Pragma: no-cache 
        Keep-Alive: timeout=5, max=100 
        Connection: Keep-Alive 
        Content-Length: 89 
        Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0 
        Content-Ty... 
Forms    : 
Headers   : {[Pragma, no-cache], [Keep-Alive, timeout=5, max=100], [Connection, Keep-Alive], [Content-Length, 89]...} 
Images   : {} 
InputFields  : {} 
Links    : {} 
ParsedHtml  : 
RawContentLength : 89 

왜 성공적으로 쿠키를 인증하지만, 파워 쉘 오류 곱슬 곱슬 않는 오류 '디코딩 실패'반환되지 않는 이유는 무엇입니까? 변수 $ websession 보면

$websession 

Headers    : {} 
Cookies    : System.Net.CookieContainer 
UseDefaultCredentials : False 
Credentials   : 
Certificates   : 
UserAgent    : Mozilla/5.0 (Windows NT; Windows NT 6.3; en-US) 
         WindowsPowerShell/5.0.10586.117 
Proxy     : 
MaximumRedirection : -1 

답변

1

Found the solution here

은 $ 데이터 변수는 API는 JSON

$data.gettype() 

IsPublic IsSerial Name          BaseType 
-------- -------- ----          -------- 
True  True  Hashtable        System.Object 

솔루션은에 $를 데이터로 변환하는 것입니다 예상 객체가되는 반면, json (ConvertTo-Json $data)

Invoke-WebRequest -Method POST ` 
-ContentType 'application/json' ` 
-Body (ConvertTo-Json $data) ` 
-Uri $url ` 
-WebSession $websession ` 
-UseBasicParsing 
관련 문제