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

PowerShell服务器查询脚本交互逻辑与异常提示问题排查

问题修复方案

错误原因分析

  1. 循环逻辑混乱:原while循环仅在输入等于'n'时执行,输入'Y'不会进入循环体,且处理逻辑后直接退出,导致无法回到初始的Y/N选择界面。
  2. 错误捕获失效:Get-ADComputer查询失败时默认抛出非终止错误,try/catch块无法捕获这类错误,因此警告提示无法触发。

修正后的脚本

while ($true) {
    $dois = Read-Host 'Server Lookup Y/N'
    $dois = $dois.ToUpper() # 统一转为大写,兼容小写输入

    switch ($dois) {
        'Y' {
            do {
                Clear-Host
                try {
                    $SN = Read-Host 'Enter Server Name'
                    # 添加-ErrorAction Stop,将非终止错误转为终止错误,让catch能捕获
                    $lookup = Get-ADComputer -Identity $SN -Properties memberof, dnshostname -ErrorAction Stop | 
                        Select-Object dnshostname, memberof |
                        ConvertTo-Json -Depth 100 | 
                        Out-File '.\extract.json'
                    # 单独调用code打开文件,避免管道覆盖$lookup的值
                    code .\extract.json
                    Write-Host "Successfully exported data for $SN" -ForegroundColor Green
                }
                catch {
                    Write-Warning "$SN does not exist, please input a valid Server Name."
                    $lookup = $null # 重置标记,继续循环输入
                }
            } until ($lookup) # 拿到有效结果后退出此循环
            # 回到外层的Y/N选择
        }
        'N' {
            Write-Host -ForegroundColor Cyan 'Ending Script'
            exit # 结束脚本
        }
        default {
            Write-Warning "Invalid input, please enter Y or N."
        }
    }
}

关键修复点

  • 重构循环结构:用while ($true)做外层循环,持续询问Y/N,直到用户输入N才退出。
  • 兼容输入格式:把用户输入转为大写,支持小写y/n的情况。
  • 强制错误捕获:给Get-ADComputer加-ErrorAction Stop参数,确保查询失败时抛出终止错误,触发catch块的警告。
  • 修正管道逻辑:将code .\extract.json从管道中移出,避免因管道最后一步无输出导致$lookup被重置为$null。
  • 添加无效输入处理:针对非Y/N的输入给出提示,引导用户正确操作。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 03:05:16