我陷入了foreach部分。我找不到任何解决方案,可以在一个foreach循环中生成2个不同的列表。我使用了2个foreach但它没有帮助。下面我分享了我的欲望输出。
我的代码:
$InStuff = @'
a
b
c
'@.Split("`n").Trim()
$InStuff2 = @'
1
2
3
'@.Split("`n").Trim()
$SPart_1 = 'application="'
$SPart_2 = ' path='
$SPart_3 = ' name='
$SPart_4 = ' application'
foreach ($IS_Item in $InStuff) {
foreach ($IS2_Item in $InStuff2) {
$UName = $IS_Item
$UName2 = $IS2_Item
$Sentence = -join (
$SPart_1, $UName,
$SPart_2, $UName2,
$SPart_3, $UName2,
$SPart_4
)
''
$Sentence
}
}
输出失败:
application="a path=1 name=1 application
application="a path=2 name=2 application
application="a path=3 name=3 application
application="b path=1 name=1 application
application="b path=2 name=2 application
application="b path=3 name=3 application
application="c path=1 name=1 application
application="c path=2 name=2 application
application="c path=3 name=3 application
我的愿望输出:
application="a path=1 name=1 application
application="b path=2 name=2 application
application="c path=3 name=3 application
谢谢
答案 0 :(得分:0)
使用for
循环:
$InStuff = @'
a
b
c
'@.Split("`n").Trim()
$InStuff2 = @'
1
2
3
'@.Split("`n").Trim()
$SPart_1 = 'application="'
$SPart_2 = ' path='
$SPart_3 = ' name='
$SPart_4 = ' application'
for ($i = 0; $i -lt $InStuff.count; $i++) {
$Sentence = -join (
$SPart_1, $InStuff[$i],
$SPart_2, $InStuff2[$i],
$SPart_3, $InStuff2[$i],
$SPart_4
), ''
$Sentence
}
如果您的输入数组的长度不同,这可能会出错,因此不安全。也许使用哈希或自定义对象会更好:
$arr = @()
$arr += new-object PSCustomObject -property @{application='a';path=1;name=1}
$arr += new-object PSCustomObject -property @{application='b';path=2;name=2}
$arr += new-object PSCustomObject -property @{application='c';path=3;name=3}
$arr | % { 'application="{0} path={1} name={2}' -f $_.application, $_.path, $_.name }
答案 1 :(得分:0)
@ arco444是对的,如果您的列表长度不同,无论您遇到什么问题。您应该重新考虑如何收集和格式化数据。这是另一种方法:
$InStuff = "a","b","c"
$InStuff2 = 1,2,3
$listCount = $InStuff.Count
$x = 0
do {
$strOut = "application= `"path = {0} name = {1} application`"" -f $InStuff[$x], $InStuff2[$x]
$strOut
$x++
}
while ( $x -lt $listCount )
在那里不确定你想要什么样的迷路"
,我添加了一个来封闭输出:
application= "path = a name = 1 application"
application= "path = b name = 2 application"
application= "path = c name = 3 application"
如果您打算使用此输出进行PowerShell的进一步处理,例如将其放入带有Export-Csv
的csv中,那么您应该放弃application
文本并改为创建对象:
$InStuff = "a","b","c"
$InStuff2 = 1,2,3
$listCount = $InStuff.Count
$x = 0
do {
[pscustomobject]@{
path = $InStuff[$x]
name = $InStuff2[$x]
}
$x++
}
while ( $x -lt $listCount )
虽然这不是你要求的,但根据我的经验,这种格式的数据更有用:
path name
---- ----
a 1
b 2
c 3
您可以添加行
[pscustomobject]@{
path = $InStuff[$x]
name = $InStuff2[$x]
}
添加其他文本(如果必须)并执行以下操作:
[pscustomobject]@{
type = "application"
path = $InStuff[$x]
name = $InStuff2[$x]
}
这将为单词application