SKLAK SKLAK - 1 year ago 101
PowerShell Question

How to check if response header contains certain headers powershell

I'm using iwr to make a request like so:

iwr "http://someapi/param" -UseBasicParsing -Method Head

This gets me the headers which looks something like this:

$var1 = "Timing-Allow-Origin: *
X-CID: 1
Accept-Ranges: bytes
Content-Length: 43
Cache-Control: public,max-age=172800
Content-Type: image/gif
Other headers

How do I check if the headers contain this:


I tried

$var2.RawContent = iwr "http://someapi/param" -UseBasicParsing -Method Head
Write-Host ($var2.RawContent -like "*Timing-Allow-Origin: *")

But this returns false for some reason. Is there a way to do this?

Answer Source

Headers returned from Invoke-Webrequest is a IDictionary. You can test by retrieving the value of the key you need.

$response = iwr "http://someapi/param" -UseBasicParsing -Method Head
if ($response.Headers["Cache-Control"] -eq "public,max-age=172800") {
    Write-Output "Found"
} else {
    Write-Output "Not found"