为什么从 Invoke-WebRequest 的结果访问某些属性会打开我的浏览器?

Why does accessing certain properties from the result from Invoke-WebRequest open my browser?

当访问我们公司内部网中的 URLs 时,通过 WIF passive authentication 进行保护,powershell 决定打开我的默认网络浏览器,并导航到我指定的 URL iwr 命令,当我访问结果的某些属性时。

当我将目标指向 google.com.

之类的东西时,这不会发生

谁能解释这种(疯狂的)行为,我该如何预防?

代码示例

$response = (Invoke-WebRequest 'http://myhost.example.com/MyApp/' -UseDefaultCredentials)
write-host $response.GetType()
write-host $response.StatusCode
$response.Forms[0] # causes browser to open, but does return the content!
# comment out the above line, and no browser opens

输出

>Microsoft.PowerShell.Commands.HtmlWebResponseObject
>200
>
>Id              Method  ...
>hiddenform      post    ...

Fiddler HTTP 摘要

GET  302  http   myhost.example.com   /MyApp/           powershell_ise
GET  401  https  sts.example.com      /default.aspx?... powershell_ise
GET  401  https  sts.example.com      /default.aspx?... powershell_ise
GET  200  https  sts.example.com      /default.aspx?... powershell_ise
GET  302  http   myhost.example.com   /MyApp/           chrome
GET  401  https  sts.example.com      /default.aspx?... chrome
GET  401  https  sts.example.com      /default.aspx?... chrome
GET  200  https  sts.example.com      /default.aspx?... chrome
POST 200  http   myhost.example.com   /MyApp/           chrome
GET  200  http   myhost.example.com   /MyApp/           chrome

我有类似行为的问题。到目前为止我发现的内容可能会帮助您缩小问题范围。

tl;dr - 添加选项 -UseBasicParsing 到请求

我有一个受 SAML 保护的 Web 服务,它使用 http 302 重定向来提供登录表单。我的脚本遵循重定向,提交表单(共有三个),并最终针对原始服务 URI 发出休息请求。

只有一个步骤会导致浏览器打开 - 当身份验证服务在 html 页面中使用预先填写的表单进行响应时,页面顶部有一些 onload(submit()) 脚本。正确的行为是立即提交表单。

导致浏览器打开的代码片段是

$results.Forms["Response"].Fields["LARES"]

我可以访问响应的任何其他部分,包括内容(其中包括原始 html 中的表单),但任何尝试评估 LARES 值或包含它的表单都会导致浏览器打开针对表单的 ACTION 属性中的完全限定 URI。

解决此问题并仍然获取数据的方法是关闭 DOM 解析,该解析迫使 Windows 使用 IE 浏览器参与。将选项 -UseBasicParsing 添加到 Invoke-WebRequest 可防止浏览器参与。这意味着 Forms[] 数组不会被填充,但 InputFields[] 数组仍然可用。

所以,而不是访问

$result.Forms["Response"].Fields["LARES"]

我现在访问

$result.InputFields[0].VALUE

其中 $result.InputFields[0].NAME 是 "LARES".