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

Powershell如何对存储服务器名的多行变量执行For循环遍历

问题根因
  • 你当前的$veriMachineNames是字符串类型,你每次通过+= "$machineNamen"`是把多个服务器名拼接成了带换行的单个长字符串,遍历的时候自然会被识别为同一个元素
  • 第二个循环用到的$sepMachineNames属于变量名拼写错误,该变量未定义,实际你存储校验后数据的变量是$veriMachineNames
修正方案

只需要把校验通过的服务器名存入数组类型的变量即可,不需要输出到文件,修正后代码如下:

$machineNames = (Read-Host "Enter Server Name(s) (space separated)").Trim()
# 初始化校验通过的变量为数组
$veriMachineNames = @()

foreach ($machineName in $machineNames.Split(' ')) {
    # 额外加空值过滤,避免多空格输入生成无效空元素
    if ([string]::IsNullOrWhiteSpace($machineName)) {
        continue
    }
    Try {
        Get-ADComputer $machineName | Out-Null
        # 直接把服务器名追加到数组
        $veriMachineNames += $machineName
    }
    Catch {
        Write-Host "*****Invalid Machine Name:  $machineName" -ForegroundColor Yellow
        Write-Host "*****Skipping $machineName`n" -ForegroundColor Yellow
    }
}

foreach ($machine in $veriMachineNames) {
    Write-Host "Server: $machine `n"
}

运行后会逐行输出每个校验通过的服务器名,你可以直接在第二个循环里编写对单台服务器执行的后续逻辑。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 03:15:03