任何人都有从COM+;使用Powershell的应用程序
我在尝试循环并从COM+应用程序中删除91个组件时遇到问题 这是我的Powershell代码:任何人都有从COM+;使用Powershell的应用程序,powershell,com+,Powershell,Com+,我在尝试循环并从COM+应用程序中删除91个组件时遇到问题 这是我的Powershell代码: $app = $apps | Where-Object {$_.Name -eq 'pkgAdap2'} $compColl = $apps.GetCollection("Components", $app.Key) $compColl.Populate() $index = 0 foreach($component in $compColl) { $compColl.Remove($in
$app = $apps | Where-Object {$_.Name -eq 'pkgAdap2'}
$compColl = $apps.GetCollection("Components", $app.Key)
$compColl.Populate()
$index = 0
foreach($component in $compColl) {
$compColl.Remove($index)
$compColl.SaveChanges()
$index++
}
代码似乎可以工作,但它只删除了一半的组件,对于$index
的其余部分,循环返回此错误:
Value does not fall within the expected range.
At line:4 char:5
+ $compColl.Remove($index)
+ ~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : OperationStopped: (:) [], ArgumentException
+ FullyQualifiedErrorId : System.ArgumentException
所以我继续运行它,剩下的组件数量不断减少一半
我认为原因是我正在从中“删除”的数组/集合会重新排序剩余的索引,每次都会移动它们。所以在$index
超出范围之前,我只通过了一半。我唯一能想到的就是这样做。因此,我也尝试了另一种方法:
while($compColl.Count > 0) {
$compColl.Remove($compColl.Count)
}
但它也不起作用
有人知道如何一次删除所有组件吗?听起来你收藏的索引是基于
0
的,所以以下方法应该有效:
while($compColl.Count -gt 0) {
$compColl.Remove($compColl.Count - 1) # remove last element, which updates .Count. Using 0 to remove the first one is a good option to.
}
$compColl.SaveChanges()
如果确定集合在枚举时不会更改,则此变体可能会稍微更有效:
for ($i = $compColl.Count - 1; $i -ge 0; --$i) {
$compColl.Remove($i)
}
$compColl.SaveChanges()
原始方法的问题是,每次调用
$compColl.Remove($index)
都会隐式减少剩余项的索引,因此$index++
最终会跳过项,直到它达到超出剩余最高索引的值并失败
一般来说,在循环体中修改集合时,逐个循环集合是有问题的。第二个集合就像一个符咒。第一个可能也有效,但决定接受你的建议。是的,我同意为什么我的版本不起作用,因为指数正在减少。