Powershell中的缩短功能

Kev*_*vin 3 powershell

当我开始进行大面积ping请求时,我首先开始在excel工作表中“写下”所有IP地址,以获取csv输出以将其导入到powershell中。

然后,我想到了通过更少的工作来使Powershell中的这些事情变得更加容易。

$range = 1..254

$ips1 = ForEach-Object -Process {'10.10.1.' + $Range}
$ips2 = ForEach-Object -Process {'10.10.2.' + $Range}
$ips3 = ForEach-Object -Process {'10.10.3.' + $Range}
$ips4 = ForEach-Object -Process {'10.10.4.' + $Range}
$ips5 = ForEach-Object -Process {'10.10.5.' + $Range}
$ips6 = ForEach-Object -Process {'10.10.6.' + $Range}
$ips7 = ForEach-Object -Process {'10.10.7.' + $Range}
$ips8 = ForEach-Object -Process {'10.10.8.' + $Range}
$ips9 = ForEach-Object -Process {'10.10.9.' + $Range}
$ips10 = ForEach-Object -Process {'10.10.10.' + $Range}
$ips11 = ForEach-Object -Process {'10.10.11.' + $Range}
$ips12 = ForEach-Object -Process {'10.10.12.' + $Range}
$ips13 = ForEach-Object -Process {'10.10.13.' + $Range}
$ips14 = ForEach-Object -Process {'10.10.14.' + $Range}
$ips15 = ForEach-Object -Process {'10.10.15.' + $Range}
$ips16 = ForEach-Object -Process {'10.10.16.' + $Range}
$ips17 = ForEach-Object -Process {'10.10.17.' + $Range}
$ips18 = ForEach-Object -Process {'10.10.18.' + $Range}
$ips19 = ForEach-Object -Process {'10.10.19.' + $Range}
$ips20 = ForEach-Object -Process {'10.10.20.' + $Range}
$ips21 = ForEach-Object -Process {'10.10.21.' + $Range}
$ips22 = ForEach-Object -Process {'10.10.22.' + $Range}
$ips23 = ForEach-Object -Process {'10.10.23.' + $Range}
$ips24 = ForEach-Object -Process {'10.10.24.' + $Range}
$ips25 = ForEach-Object -Process {'10.10.25.' + $Range}
$ips26 = ForEach-Object -Process {'10.10.26.' + $Range}
$ips27 = ForEach-Object -Process {'10.10.27.' + $Range}
$ips28 = ForEach-Object -Process {'10.10.28.' + $Range}
$ips29 = ForEach-Object -Process {'10.10.29.' + $Range}
Run Code Online (Sandbox Code Playgroud)

所以我到了这一点,但现在我陷入了困境,我如何使它变得更短而没有错误,所以之后我有了一个大变量,它将所有ip存储在一个变量中

Mar*_*agg 8

这是一个较短的解决方案,其结果与您的代码相同:

ForEach ($Network in 1..29) {
    $IPAddresses = ForEach ($IP in 1..254) {
        "10.10.$Network.$IP"
    }

    New-Variable -Name IPs$Network -Value $IPAddresses
}
Run Code Online (Sandbox Code Playgroud)

要获得具有所有IP的单个变量,请执行以下操作:

$AllIPs = ForEach ($Network in 1..29) {
    ForEach ($IP in 1..254) {
        "10.10.$Network.$IP"
    }   
}
Run Code Online (Sandbox Code Playgroud)

  • 这正是我想做的,因为我试图弄清楚我在尝试仅在一个foreach中执行操作时遇到错误,应该更容易实现,谢谢:) (2认同)