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

PowerShell中如何通过输入ID值获取对应服务器Name列内容

实现方法

1. 完整修改后的脚本

在现有脚本基础上添加用户输入、验证及匹配逻辑,就能实现输入ID获取对应服务器名称的功能:

### OU of servers
$DNAServers = "OU=Location,OU=Servers,DC=Company,DC=internal"

### Server List
$ServerList = Get-ADComputer -Filter * -SearchBase $DNAServers -Properties Name, Description | 
              Select-Object Name, Description | 
              Sort-Object Description

# 添加ID列并保存到变量
$Global:i = 0
$ServerID = $ServerList | Select-Object @{ Name = 'ID'; Expression = { $global:i.ToString("00"); $global:i += 1 } }, *

# 显示服务器列表供用户参考
$ServerID

# 获取并验证用户输入的ID
do {
    $inputID = Read-Host "请输入服务器ID(如00)"
    # 确保输入为两位数字格式
    $isValid = $inputID -match '^\d{2}$'
    if (-not $isValid) {
        Write-Host "错误:请输入两位数字格式的ID(例如00、05)" -ForegroundColor Red
    }
} while (-not $isValid)

# 根据ID查找对应服务器名称
$selectedServer = $ServerID | Where-Object { $_.ID -eq $inputID }

# 输出结果
if ($selectedServer) {
    Write-Host "`n对应服务器名称:$($selectedServer.Name)" -ForegroundColor Green
} else {
    Write-Host "`n未找到ID为$inputID的服务器" -ForegroundColor Red
}

2. 关键逻辑说明

  • 输入验证:通过正则表达式^\d{2}$强制用户输入两位数字,避免格式错误导致匹配失败
  • 数据匹配:用Where-Object在已生成的$ServerID集合中筛选ID完全匹配的记录
  • 结果反馈:用不同颜色区分成功/失败提示,让输出更直观

3. 运行流程

  1. 从指定OU拉取服务器数据,按Description排序并生成两位格式的ID列
  2. 展示完整服务器列表供用户查看
  3. 循环提示用户输入ID,直到输入符合格式要求
  4. 查找并输出对应服务器名称,或提示未找到匹配项

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.02 07:20:41