Powershell-foreach循环过早退出?
请原谅,我对Powershell很陌生。我很难理解为什么我的代码在找到ID为“bk103”的书时突然退出foreach循环。我希望foreach循环在for循环中迭代12次,因为xml文件中有12本书。为什么提前退出 谢谢大家!Powershell-foreach循环过早退出?,powershell,Powershell,请原谅,我对Powershell很陌生。我很难理解为什么我的代码在找到ID为“bk103”的书时突然退出foreach循环。我希望foreach循环在for循环中迭代12次,因为xml文件中有12本书。为什么提前退出 谢谢大家! Set-Location 'C:\PowershellPractice\' #' [int]$index = 0 [stri
Set-Location 'C:\PowershellPractice\' #'
[int]$index = 0
[string] $xmlFilePath=’C:\PowershellPractice\books.xml’
[xml] $xmlContent = [xml] (Get-Content -Path $xmlFilePath)
$newSubNode = $xmlContent.CreateElement("security")
$newSubNode.SetAttribute("Mode", "transport")
$collection = $xmlContent.catalog.ChildNodes
Write-Host "Collection has " $collection.Count " elements in it!"
foreach ($item in $collection){
Write-Host "In foreach, index is " $index
if ($item.id -eq "bk103" -OR
$item.id -eq "bk105" -OR
$item.id -eq "bk108" -OR
$item.id -eq "bk109"){
Write-Host "Found book called " $ $item.id
$elementCopy = $xmlContent.catalog.book[$index].Clone()
$elementCopy.AppendChild($newSubNode)
$xmlContent.catalog.RemoveChild($item)
$xmlContent.catalog.InsertBefore($elementCopy,$xmlContent.catalog.book[$index])
}
$index++
}
$xmlContent.Save('C:\PowershellPractice\books-edited.xml')
如注释中所述,当您当前正在对集合进行迭代时,无法修改该集合 因为您实际上只需要修改集合中的元素本身,所以我建议您这样做(而不是克隆
book
节点并重新附加它):
如果您发现自己处于无法就地修改元素的情况下,请使用两个循环—一个用于查找感兴趣的元素,另一个用于通过迭代生成的子集来替换它们:
# collect matching results
$foundbooks = foreach ($item in $collection){
Write-Host "In foreach, index is " $index
if ($item.id -eq "bk103" -OR
$item.id -eq "bk105" -OR
$item.id -eq "bk108" -OR
$item.id -eq "bk109"){
# return matching $item
$item
}
}
# now modify based on initial results
foreach($book in $foundbooks){
Write-Host "Found book called " $ $book.id
$elementCopy = $book.Clone()
[void]$elementCopy.AppendChild($newSubNode)
[void]$xmlContent.catalog.InsertBefore($elementCopy,$book)
[void]$xmlContent.catalog.RemoveChild($book)
}
这是一个错误吗?可能吧?根本没有错误。它存在是因为您修改了
$collection
您正在迭代Hanks Mathias,编写代码的更好方法是什么?在foreach循环中收集所需的信息,而不实际修改$xmlContent
——然后使用另一个循环迭代第一个循环的结果,并执行实际的删除/添加操作。我会写一个恰当的回答谢谢Mathias!我对此进行了测试,但仍然没有达到预期效果。代码所做的是,它只将新元素添加到bk109中,而没有添加到其余的3本书(bk103、bk105、bk108)中。虽然我在上有断点,但我确实注意到了奇怪的行为。我在最后一个for循环中运行了save命令,以便在添加子节点并删除原始节点后,将更改保存到文件中。当我继续进行for循环时,新节点被添加到bk103,但在随后的迭代中它移动到bk105。
# collect matching results
$foundbooks = foreach ($item in $collection){
Write-Host "In foreach, index is " $index
if ($item.id -eq "bk103" -OR
$item.id -eq "bk105" -OR
$item.id -eq "bk108" -OR
$item.id -eq "bk109"){
# return matching $item
$item
}
}
# now modify based on initial results
foreach($book in $foundbooks){
Write-Host "Found book called " $ $book.id
$elementCopy = $book.Clone()
[void]$elementCopy.AppendChild($newSubNode)
[void]$xmlContent.catalog.InsertBefore($elementCopy,$book)
[void]$xmlContent.catalog.RemoveChild($book)
}