I am trying to implement a ReST request in PowerShell.
Request 1:
$response = Invoke-RestMethod "my-custom-url" -Headers $headers -Method POST -Body $json -ContentType "application/json" -OutFile output.json -SessionVariable sv
Reponse from Request 1:
{
"@type": "user",
"id": "00000703000000000010",
"orgId": "000007",
"name": "[email protected]",
}
I need to save the value of "id" & add it to the header of next request. How can I achieve that?
----Update--Adding the WriteHost $response
@{@type=user; id=00000703000000000010; orgId=000007; name=xxx; createTime=2014-08-27T12:12:21.000Z; updateTime=2016-02-27
T00:40:13.000Z; [email protected]; updatedBy=xxx; sfUsername=ppanigrahi; firstName=Pravakar; lastName=P
anigrahi; password=********; phone=9008433201; [email protected]; timezone=IST; serverUrl=http://localhost:16006/saas; spiUrl
=https://localhost:8080/; icSessionId=QpXZEkqYEflJRY7h; securityQuestion=MOTHER_MAIDEN_NAME; forceChangePassword=False; uuid=C1bL60uIQqyRaF3
nXCHFkA; roles=System.Object[]; usergroups=System.Object[]}
Since you're using Invoke-RestMethod, the response will be an object containing the properties with the data and you can access the id from the $Response.id.
I'm not sure if you want to try to pass the "Id" as a header value or as a cookie (as you're referring to your session variable also; where you'd normally persist e.g. cookies etc).
If all you want is to pass a custom-header containing the field "Id" you can do the following before the next request:
$headers.Add("Id",$response.id);
I'm assuming you've defined $headers on beforehand here. Else you can create it directly with $headers = @{"Id"=$response.id};.
Then on the next service call just reuse your $headers variable as you allready did.
If what you really are trying to achieve is to create a cookie and add this one to your session (variable) so you don't have to repeat yourself for every subsequent call; you should create a cookie and add it doing the following:
$c=New-Object System.Net.Cookie;
$c.Name="Id";
$c.Path="/"
$c.Value = $response.Id;
# Make sure domain and path is matching your backend-server
$c.Domain = "foobar.com";
# Add cookie to your websession
$sv.Cookies.Add($c);
This will create a cookie and add it to your websession (if $sv is in your session). If you don't have a webrequest session ($sv in your case), you can create this on before hand using $sv = New-Object Microsoft.PowerShell.Commands.WebRequestSession;