16

For some reason this doesn't work

Invoke-RestMethod -Uri "http://localhost" -Headers @{"Host"="web.domain.com"}

I get the error

The 'Host' header must be modified using the appropriate property or method

But I can't find the method or property on how to do this.

Thanks

2
  • 3
    What version of powershell are you using? Your tags says 2.0, but I don't believe Invoke-RestMethod was added until 3.0. I was able to use the exact command you provided above without error on Powershell 4.0 on Windows 8.1. Commented Nov 12, 2013 at 19:26
  • I'm using powershell v3.0 Commented Nov 13, 2013 at 10:14

2 Answers 2

20

This is a bug that has been fixed in PowerShell version 4.0:

C:\PS> (irm http://localhost -Headers @{Host='web.domain.com'}).html

xmlns                                   head                                    body
-----                                   ----                                    ----
http://www.w3.org/1999/xhtml            head                                    body
Sign up to request clarification or add additional context in comments.

2 Comments

So what's the work around? I see the table that you pasted, but I'm not sure what I'm really looking at.
This is just showing that the OP's command works in PowerShell V4 by showing the "HTML" returned by the request. In tabular format, this is just showing the XML namespace decl and the head and body element tags.
7

For the record I worked round the issue using WebRequest

$bytes = [system.Text.Encoding]::UTF8.GetBytes("key=value")
$web = [net.WebRequest]::Create("http://localhost") -as [net.HttpWebRequest]
$web.ContentType = "application/x-www-form-urlencoded"
$web.Host = "web.domain.com"
$web.Method = "POST"
$web.ContentLength = $bytes.Length
$stream = $web.GetRequestStream()
$stream.Write($bytes,0,$bytes.Length)

2 Comments

With this do you ever see the error "You must write ContentLength bytes to the request stream before calling [Begin]GetResponse"?
I am trying to create the header for cloudflare. I am not able to determine the host and keep getting a 421 misdirected request

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.