在使用范围运算符时尝试附加名称列表

Trying to append a list of names while using a range operator

尝试做这样的事情:

$BaseCompName = ProdServer-
$CompNameSuffix = 1..45
$ServerName = "$BaseCompName" + "$CompNameSuffix"

我们的想法是生成一个列表 - 在 RAM、TXT 文件或 CSV 文件中 - 看起来像

ProdServer-1
ProdServer-2
ProdServer-3
...
ProdServer-45

从那个列表中,我会使用 ForEach 或类似的东西,通过 Test-Connection 或类似的东西对它们执行 ping 命令,然后将该数据添加到文件或我们的任何东西中d正在处理当时的数据。

我不太确定如何构造它。我见过有人使用范围运算符来 ping 一堆 IP 的例子,但是,每当我试图从中拼凑一些东西时,它就会惨败。我重新安排事情,我看到越来越多的错误。现在,我迷路了,一切都开始看起来一样了。

我最近的尝试:

$CompName = 1..45
$Servers = "PRODSERVER-" + $CompName
ForEach ($Server in $Servers) { 
    Test-Connection -ComputerName $Server -Count 1 }| Export-Csv 'C:\Users\SucksAtPowerShell\Desktop\ips.csv' -NoTypeInformation }

如前所述,中断...

Test-Connection : Testing connection to computer 'PRODSERVER-1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 
    19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45' failed: The requested 
    name is valid, but no data of the requested type was found
    At line:4 char:5
    +     Test-Connection -ComputerName $Server -Count 1 }
    +     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
        + CategoryInfo          : ResourceUnavailable: (PRODSERVER-1 2 ... 41 42 43 44 45:String) [Test-Conne
      ction], PingException
        + FullyQualifiedErrorId : TestConnectionException,Microsoft.PowerShell.Commands.TestConnectionCommand

您没有遍历每个数组元素。当转换为字符串时,您的数组只是与由 space.

分隔的每个元素连接

对此有多种方法,但大多数涉及在循环内处理整数数组。让我们将范围运算符移动到 ForEach-Object

的管道输入中
1..45 | ForEach-Object {
    $Server =  "PRODSERVER-$_"
    Test-Connection -ComputerName $Server -Count 1
} | Export-Csv 'C:\Users\SucksAtPowerShell\Desktop\ips.csv' -NoTypeInformation 

或者更符合您之前的内容

$CompName = 1..45
$Servers = $CompName | ForEach-Object{"PRODSERVER-" + $_}