我正在从一个 API 中提取一些数据,我最终以两个字符串的形式存储了这些数据,看起来像这样:
$String1
:
客户 1 客户 2 客户 3
$String2
:
产品 a 产品 b 产品 c
以上是现实中的一长串清单。
我还从存储在数组中的不同 API 获取了一组不同的数据。
$Array
:
Server State
abcd.com Normal
defg.com Dead
fguy.com Normal
请注意,我要取的方式$String1
,并$String2
从提取为不同的API输出服务器的foreach的价值观findstr Client
和findstr Product
。
现在,我想从这 3 美元中获得一个最终表,它看起来像这样:
$Final
:
Server State Client Product
abcd.com Normal 1 a
defg.com Dead 2 b
fguy.com Normal 3 c
所以我首先尝试做的是创建和中间表,它可能看起来像
Client Product
1 a
2 b
3 c
然后与 合并$Array
到最终表中。
而目前我对此无所适从,我尝试了很多不同的方法,这些方法看起来很愚蠢而且一无所获。
由于它看起来像是$Array3
一个具有两个属性的对象数组:Server
and State
,我认为这可以帮助您:
$Array1 = 'Client 1','Client 2','Client 3'
$Array2 = 'Product a','Product b','Product c'
$Array3 = @(
[PsCustomObject]@{'Server' = 'abcd.com'; 'State' = 'Normal'},
[PsCustomObject]@{'Server' = 'defg.com'; 'State' = 'Dead'},
[PsCustomObject]@{'Server' = 'fguy.com'; 'State' = 'Normal'}
)
for ($i = 0; $i -lt $Array3.Count; $i++) {
$Array3[$i] | Select-Object *,
@{Name = 'Client'; Expression = { $Array1[$i] -replace '^Client\s*'}},
@{Name = 'Product'; Expression = { $Array2[$i] -replace '^Product\s*'}}
}
输出:
Server State Client Product ------ ----- ------ ------- abcd.com Normal 1 a defg.com Dead 2 b fguy.com Normal 3 c
如果需要,您可以捕获 for(..) 循环的结果并将其另存为 CSV 文件。在那种情况下就做
$result = for ($i = 0; $i -lt $Array3.Count; $i++) {
$Array3[$i] | Select-Object *,
@{Name = 'Client'; Expression = { $Array1[$i] -replace '^Client\s*'}},
@{Name = 'Product'; Expression = { $Array2[$i] -replace '^Product\s*'}}
}
$result | Export-Csv -Path 'D:\serverresult.csv' -NoTypeInformation
在这种情况下,拆分这些字符串中的行,这样您最终会得到真正的数组:
$string1 = @"
Client 1
Client 2
Client 3
"@
$string2 = @"
Product a
Product b
Product c
"@
# split the multiline strings (examples) on the Newline character into arrays
$Array1 = $string1 -split '\r?\n'
$Array2 = $string2 -split '\r?\n'
# now, both arrays will have 3 elements:
# $Array1 = 'Client 1','Client 2','Client 3'
# $Array2 = 'Product a','Product b','Product c'
# array no. 3 is an array of objects as we saw earlier
$Array3 = @(
[PsCustomObject]@{'Server' = 'abcd.com'; 'State' = 'Normal'},
[PsCustomObject]@{'Server' = 'defg.com'; 'State' = 'Dead'},
[PsCustomObject]@{'Server' = 'fguy.com'; 'State' = 'Normal'}
)
# Finally, you can use the `for(..)` loop unaltered
$result = for ($i = 0; $i -lt $Array3.Count; $i++) {
$Array3[$i] |
Select-Object *,
@{Name = 'Client'; Expression = { $Array1[$i] -replace '^Client\s*'}},
@{Name = 'Product'; Expression = { $Array2[$i] -replace '^Product\s*'}}
}
# output on console
$result
# output to CSV file
$result | Export-Csv -Path 'D:\serverresult.csv' -NoTypeInformation
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句