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

PowerShell代理查询脚本默认输入分支异常问题求助

你的脚本核心问题是Read-Host按下回车时返回的是空字符串("")而非$null,原脚本里的IF($null -eq $promptOutput)条件永远不会触发,所以按回车时直接跳去ELSE分支执行单台查询逻辑,自然报错。

修复步骤

  1. 修正分支判断条件:用[string]::IsNullOrEmpty($promptOutput)替代原条件,这个方法能同时判断变量是否为$null或者空字符串,完美匹配按回车的场景。
  2. 补充列表读取逻辑:原IF分支里的$sysName变量未定义,需要先从testlist.txt读取机器列表,否则循环会报错。
  3. 优化脚本安全性与兼容性:
    • 用Get-CimInstance替代过时的Get-WmiObject
    • 避免拼接字符串生成脚本块的不安全写法,直接在远程脚本块内完成SID获取和注册表查询

修改后的完整脚本

$ErrorActionPreference = "SilentlyContinue"

$pathHKU = 'HKU:\.Default\Environment\'
$pathExists = Test-Path -Path $pathHKU

If(!($pathExists)) { 
    New-PSDrive -PSProvider Registry -Name HKU -Root HKEY_Users | Out-Null
}

$promptOutput = Read-Host "Press enter to search by list or type in the name of a single machine []"

# 修正判断条件:匹配空输入或null
IF([string]::IsNullOrEmpty($promptOutput)) {
    # 读取机器列表文件
    $sysName = Get-Content -Path ".\testlist.txt"
    ForEach ($sys in $sysName) {
        # 远程获取当前登录用户的SID并查询代理设置
        $userProxy = Invoke-Command -ComputerName $sys -ScriptBlock {
            $userName = Get-CimInstance Win32_ComputerSystem | Select-Object -ExpandProperty Username
            if ($userName) {
                $sid = ([System.Security.Principal.NTAccount]$userName).Translate([System.Security.Principal.SecurityIdentifier]).Value
                Get-ItemPropertyValue "registry::HKU\$sid\Software\Microsoft\Windows\CurrentVersion\Internet Settings" -Name ProxyServer -ErrorAction SilentlyContinue
            }
        }
        # 将结果写入CSV
        "$sys - $userProxy" | Out-File -Path ".\TestProxySettings.csv" -Append
    }
}else{
    $nameComp = $promptOutput
    # 单台机器查询逻辑同样优化
    $userProxy = Invoke-Command -ComputerName $nameComp -ScriptBlock {
        $userName = Get-CimInstance Win32_ComputerSystem | Select-Object -ExpandProperty Username
        if ($userName) {
            $sid = ([System.Security.Principal.NTAccount]$userName).Translate([System.Security.Principal.SecurityIdentifier]).Value
            Get-ItemPropertyValue "registry::HKU\$sid\Software\Microsoft\Windows\CurrentVersion\Internet Settings" -Name ProxyServer -ErrorAction SilentlyContinue
        }
    }
    Write-Host "$nameComp - $userProxy"
}

关键修改说明

  • 分支判断改用[string]::IsNullOrEmpty(),精准匹配按回车的空输入场景
  • 移除了冗余的脚本块拼接逻辑,直接在远程会话内完成所有操作,避免注入风险
  • 添加了-ErrorAction SilentlyContinue处理注册表查询失败的情况(比如用户未登录或无代理设置)
  • 用Get-CimInstance替代Get-WmiObject,提升兼容性和性能
  • 补充了$sysName的读取逻辑,确保列表查询分支能正常读取机器名

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.21 11:22:13