I wrote a small PowerShell script to send a request to a server and get a simple XML result back.
PowerShell Script
$xml = \"
I went ahead and looked into the Invoke-WebRequest
cmdlet code and found out why it's failing with this particular error.
It's failing on a call to System.Globalization.EncodingTable.GetCodePageFromName
. The encoding is passed to that function as a parameter and the encoding is retrieved from the the cmdlet through the Content-Type
header. In the case of this server the Content-Type was sent back in the response as Content-Type: application/xml; charset="UTF-8"
.
The problem with this is that quotes aren't standard for wrapping the value in charset
so the cmdlet parses it out as "UTF-8"
instead of the valid UTF-8
. The cmdlet passes "UTF-8"
to the function and the function throws an exception stating that the provided encoding is invalid. This is fine and would make so much more sense if that is what was reported in the final exception but it's not.
The Invalid encoding exception is caught by the Microsoft.PowerShell.Commands.ContentHelper.GetEncodingOrDefault
function and in the exception handler it calls GetEncoding
again but with a null parameter which results in the final ArgumentNullException
for parameter name
.
Microsoft.PowerShell.Commands.ContentHelper.GetEncodingOrDefault
internal static Encoding GetEncodingOrDefault(string characterSet)
{
string name = string.IsNullOrEmpty(characterSet) ? "ISO-8859-1" : characterSet;
try
{
return Encoding.GetEncoding(name);
}
catch (ArgumentException ex)
{
return Encoding.GetEncoding((string) null);
}
}
The call to GetEncoding
inside the catch statement triggers the following code inside GetCodePageFromName
which is itself called from GetEncoding
if (name==null) {
throw new ArgumentNullException("name");
}
PowerShell is handling this properly since technically it is an invalid value but you'd think they would call Trim("\"")
just to be safe.