二次数组迭代
Two array iteration
我对 PowerShell 还很陌生,正在学习如何做一些事情。我有两个具有相同数量对象的非常大的数组。如何同时迭代两个数组。
示例:
$first = @(
'First'
'Second'
...
)
$second = @(
'one'
'two'
...
)
我需要配对对象并像这样打印它:
First one
Second two
我尝试使用 foreach,但不知道如何使用。我也尝试“for”循环,但总是打印混乱。
一些代码示例帮助将不胜感激。提前谢谢你。
更新:
这是我使用的代码
$All = @( '1.1.1.1/80' '2.2.2.2/443' '3.3.3.3/8883' )
$AllProtocols = @( 'HTTP' 'HTTPS' 'TCP' )
$All | ForEach-Object -Begin $null -Process {
$Ip = $_.Split("/")[0]
$Port = $_.Split("/")[1]
$AllProtocols | ForEach-Object -Begin $null -Process {
$Protocol = $_
$Test = New-Object PSObject -Property @{
RemoteAddress = $Ip
LocalPort = $Port
Protocol = $Protocol
}
$Ip
$Port
$Protocol
Write-Host "RemoteAddress $($Test.RemoteAddress) LocalPort $($Test.LocalPort) Protocol $($Test.Protocol)"
} -End $null
} -End $null
首先,您定义的数组在不同值之间缺少逗号。
你用空格编码的方式是错误的(编辑应该已经告诉你了)。
此外,当您要声明多个值时,就不需要 @()
构造。
然后,你让这比它应该的更难了。为什么不使用简单的计数器循环来迭代索引上的数组?
$All = '1.1.1.1/80','2.2.2.2/443','3.3.3.3/8883'
$AllProtocols = 'HTTP', 'HTTPS', 'TCP'
for ($i = 0; $i -lt $All.Count; $i++) {
$ip, $port = $All[$i] -split '/'
[PsCustomObject]@{
RemoteAddress = $ip
LocalPort = $port
Protocol = $AllProtocols[$i]
}
}
结果:
RemoteAddress LocalPort Protocol
------------- --------- --------
1.1.1.1 80 HTTP
2.2.2.2 443 HTTPS
3.3.3.3 8883 TCP
当然,这只会输出到控制台,但是如果您像 $result = for ($i = 0; $i -lt $All.Count; $i++) { .. }
这样从变量中捕获循环的结果,您可以将它保存到 CSV 文件中作为奖励。
我对 PowerShell 还很陌生,正在学习如何做一些事情。我有两个具有相同数量对象的非常大的数组。如何同时迭代两个数组。
示例:
$first = @(
'First'
'Second'
...
)
$second = @(
'one'
'two'
...
)
我需要配对对象并像这样打印它:
First one
Second two
我尝试使用 foreach,但不知道如何使用。我也尝试“for”循环,但总是打印混乱。
一些代码示例帮助将不胜感激。提前谢谢你。
更新: 这是我使用的代码
$All = @( '1.1.1.1/80' '2.2.2.2/443' '3.3.3.3/8883' )
$AllProtocols = @( 'HTTP' 'HTTPS' 'TCP' )
$All | ForEach-Object -Begin $null -Process {
$Ip = $_.Split("/")[0]
$Port = $_.Split("/")[1]
$AllProtocols | ForEach-Object -Begin $null -Process {
$Protocol = $_
$Test = New-Object PSObject -Property @{
RemoteAddress = $Ip
LocalPort = $Port
Protocol = $Protocol
}
$Ip
$Port
$Protocol
Write-Host "RemoteAddress $($Test.RemoteAddress) LocalPort $($Test.LocalPort) Protocol $($Test.Protocol)"
} -End $null
} -End $null
首先,您定义的数组在不同值之间缺少逗号。
你用空格编码的方式是错误的(编辑应该已经告诉你了)。
此外,当您要声明多个值时,就不需要 @()
构造。
然后,你让这比它应该的更难了。为什么不使用简单的计数器循环来迭代索引上的数组?
$All = '1.1.1.1/80','2.2.2.2/443','3.3.3.3/8883'
$AllProtocols = 'HTTP', 'HTTPS', 'TCP'
for ($i = 0; $i -lt $All.Count; $i++) {
$ip, $port = $All[$i] -split '/'
[PsCustomObject]@{
RemoteAddress = $ip
LocalPort = $port
Protocol = $AllProtocols[$i]
}
}
结果:
RemoteAddress LocalPort Protocol
------------- --------- --------
1.1.1.1 80 HTTP
2.2.2.2 443 HTTPS
3.3.3.3 8883 TCP
当然,这只会输出到控制台,但是如果您像 $result = for ($i = 0; $i -lt $All.Count; $i++) { .. }
这样从变量中捕获循环的结果,您可以将它保存到 CSV 文件中作为奖励。