You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将PowerShell 5.1的网页登录代码适配PowerShell 7环境运行

解决方案

Windows PowerShell 5.1 中的 Invoke-WebRequest 依赖IE内核的COM组件实现HTML解析,会自动提取页面内的表单结构填充到Forms属性中;PowerShell 7.x作为跨平台版本移除了对IE组件的依赖,默认不会自动解析表单,因此不存在Forms相关属性。

方案1:Windows宿主Azure Function兼容方案

如果你的Azure Function App使用Windows系统作为运行宿主,可以直接在请求登录页的Invoke-WebRequest中添加-UseBasicParsing:$false参数,即可复用原有逻辑,改后代码如下:

$url = "mysite.com/login"
# 仅添加了 -UseBasicParsing:$false 参数,其余逻辑和原有代码完全一致
$r=Invoke-WebRequest -Uri $url -UseDefaultCredentials -SessionVariable RequestForm -UseBasicParsing:$false
$fields = $r.Forms[0].Fields
$fields['field_id1'] = 'myusername'
$fields['field_id2'] = 'secretPass'
$fields['__EVENTTARGET'] = 'btnLogin'
$response = Invoke-WebRequest -Uri $url -WebSession $RequestForm -Method POST -Body $fields -ContentType 'application/x-www-form-urlencoded'

注意:该方案仅适用于Windows运行环境,Linux/macOS宿主不支持。

方案2:跨平台通用方案(推荐)

如果你使用Linux宿主的Function App,或者需要保证代码的跨平台兼容性,可以手动解析HTML提取表单字段,无需依赖内置的表单解析能力,改后代码如下:

$url = "mysite.com/login"
# 请求登录页,保留会话
$r = Invoke-WebRequest -Uri $url -UseDefaultCredentials -SessionVariable RequestForm
$htmlContent = $r.Content

# 正则匹配所有input标签的name和value属性,构造表单字段哈希表
$fields = @{}
$inputPattern = '<input[^>]*name="([^"]+)"[^>]*value="([^"]*)"'
$matches = [regex]::Matches($htmlContent, $inputPattern, [System.Text.RegularExpressions.RegexOptions]::IgnoreCase)
foreach ($match in $matches) {
    $name = $match.Groups[1].Value
    $value = $match.Groups[2].Value
    $fields[$name] = [System.Web.HttpUtility]::HtmlDecode($value)
}

# 填充自定义字段
$fields['field_id1'] = 'myusername'
$fields['field_id2'] = 'secretPass'
$fields['__EVENTTARGET'] = 'btnLogin'

# 提交登录请求
$response = Invoke-WebRequest -Uri $url -WebSession $RequestForm -Method POST -Body $fields -ContentType 'application/x-www-form-urlencoded'

注意事项

  • 如果表单的提交地址和当前登录页地址不一致,可以额外匹配form标签的action属性作为POST的目标地址
  • 若页面存在多个表单,可以调整正则匹配逻辑,先定位到你需要提交的表单块内再提取input字段

内容的提问来源于stack exchange,提问作者Vital

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.03 01:15:04