简体   繁体   中英

In Powershell, how do I pull specific text from an object that was returned by an API response?

New to Powershell here so any advice is appreciated. I'm Posting to this website's API (I code-named it authenticate.com in the below code) to receive in the response an auth token as a cookie. The next objective is to take the cookie and use it to validate to a different API? How can I capture the auth-token returned by the first API and save it into a variable?

My code:

$Url = 'https://authenticate.com/apikeylogin'
$auth = @{
     keyPublic= '********************'
     keySecret= '********************'
}
$json = $auth | ConvertTo-Json
$response = Invoke-WebRequest $Url -Method Post -Body $json -ContentType 'application/json'
$response | Get-Member
$response.RawContent

The response in raw-text:

HTTP/1.1 200 OK
auth-token: ******************
[Below this is are a dozen more lines of raw data]

To restate the question, how do I get the above value of 'auth-token' and store it into a variable?

You can use Select-String (similar to grep in powershell) to figure out the line containing the auth-token and get the auth-token value.

$response = "HTTP/1.1 200 OK `
auth-token: ABCDEFGHIJKLMNOP `
[Below this is are a dozen more lines of raw data]"

$authTokenline =
 $response.Split("`n") | Select-String -Pattern "^auth-token:.*$" 
$authToken = $authTokenline.ToString().Split(":")[1]
ABCDEFGHIJKLMNOP

Ok, I have solved the problem using.Substring()

$auth = @{
     keyPublic= '********************'
     keySecret= '********************'
}
$json = $auth | ConvertTo-Json
$response = Invoke-WebRequest $Url -Method Post -Body $json -ContentType 'application/json'
$raw = $response.RawContent
$string = $raw | Out-String
$auth_token = $string.Substring(35, 90)

The access token I am requesting from the API always has the same length so I used the substring method to pinpoint exactly which chars from the string are what I need and then store them in the variable "auth-token"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM