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

PowerShell脚本优化需求:支持用户ID/PC名输入并获取有效用户ID

实现支持用户ID/PC名输入的PowerShell脚本改进方案

以下是满足需求的完整PowerShell脚本实现,包含输入选择、PC名映射、AD校验及错误处理逻辑:

# 导入PC与用户关联的CSV文件(请替换为实际CSV路径)
$pcUserMapping = Import-Csv -Path "C:\Path\To\Your\PC-User-Map.csv"

# 获取用户输入类型选择,确保输入有效
do {
    $inputType = Read-Host "请选择输入类型:`n1 - 直接输入用户ID`n2 - 输入PC名获取用户ID"
} while ($inputType -notin @("1", "2"))

$userName = $null

switch ($inputType) {
    "1" {
        # 直接输入用户ID流程,校验AD中存在性
        do {
            $inputValue = Read-Host "请输入用户ID"
            $adUser = Get-ADUser -Filter "SamAccountName -eq '$inputValue'" -ErrorAction SilentlyContinue
            if (-not $adUser) {
                Write-Host "错误:输入的用户ID在Active Directory中不存在,请重新输入。" -ForegroundColor Red
            } else {
                $userName = $adUser.SamAccountName
            }
        } while (-not $userName)
    }
    "2" {
        # 通过PC名获取用户ID流程
        do {
            $inputValue = Read-Host "请输入PC名(需以BN开头)"
            # 校验PC名格式合规性
            if (-not $inputValue.StartsWith("BN")) {
                Write-Host "错误:PC名必须以BN开头,请重新输入。" -ForegroundColor Red
                continue
            }
            # 从CSV映射表查找对应用户ID
            $mappingEntry = $pcUserMapping | Where-Object { $_.PCName -eq $inputValue }
            if (-not $mappingEntry) {
                Write-Host "错误:未找到该PC名对应的用户ID,请重新输入。" -ForegroundColor Red
                continue
            }
            # 校验映射得到的用户ID在AD中是否存在
            $adUser = Get-ADUser -Filter "SamAccountName -eq '$($mappingEntry.UserID)'" -ErrorAction SilentlyContinue
            if (-not $adUser) {
                Write-Host "错误:该PC名关联的用户ID在Active Directory中不存在,请联系管理员确认映射关系。" -ForegroundColor Red
                continue
            }
            $userName = $adUser.SamAccountName
        } while (-not $userName)
    }
}

# 后续业务逻辑可直接使用$userName变量
Write-Host "已确认有效用户ID:$userName" -ForegroundColor Green

关键功能说明

  • CSV映射导入:通过Import-Csv加载预定义的PC-用户关联数据,需确保CSV包含PCName(PC名列)和UserID(用户ID列),可根据实际CSV结构调整列名。
  • 输入合法性校验:通过循环强制用户选择有效的输入类型,避免无效值进入后续流程。
  • PC名合规检查:强制验证输入的PC名以BN开头,符合需求规范;无匹配映射时给出明确的自定义错误提示。
  • AD用户有效性校验:无论通过哪种输入方式获取的用户ID,都会校验其在Active Directory中的存在性,确保后续命令使用合法的用户ID。
  • 变量一致性保障:最终$userName始终存储经过AD校验的用户ID,不会存储PC名,严格满足需求要求。

注意事项

  • 需确保脚本运行环境已安装Active Directory模块,可通过命令Install-WindowsFeature RSAT-AD-PowerShell安装。
  • 替换脚本中的CSV文件路径为实际存储路径,确保CSV格式正确(表头为PCName,UserID,每行对应一条PC-用户关联记录)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.21 03:18:40