如何从PowerShell中的ForEach

如何从PowerShell中的ForEach

本文介绍了如何从PowerShell中的ForEach-Object退出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码:

  $ project.PropertyGroup | Foreach {
if($ _。GetAttribute('Condition')。Trim()-eq $ propertyGroupConditionName.Trim()){
$ a = $ project.RemoveChild($ _);
Write-Host $ _。GetAttribute('Condition')已被删除。
}
};

问题#1:如何退出ForEach?我试过使用break和continue,但是它不起作用。

问题2:我发现我可以在循环...我们不能这样做,在C#中...为什么PowerShell允许我们这样做?

解决方案

项目#1。在 foreach 循环中放置 break 会退出循环,但不会停止管道。这听起来像你想要的东西是这样的:
$ b $ pre $ $ $ $ $ $ $ $ $ foreach $ $ $ $ todo){
if($ thing -eq'some_condition'){
break
}
}

项目#2。 PowerShell允许你修改一个数组内的 foreach 循环内的数组,但是这些变化直到退出循环才会生效。尝试运行下面的代码作为例子。

  $ a = 1,2,3 
foreach($ value in $ a){
写主机$值
}
写主机$ a

我不能评论为什么PowerShell的作者允许这样做,但大多数其他脚本语言(和shell)允许类似的结构。


I have the following code:

$project.PropertyGroup | Foreach {
    if($_.GetAttribute('Condition').Trim() -eq $propertyGroupConditionName.Trim()) {
        $a = $project.RemoveChild($_);
        Write-Host $_.GetAttribute('Condition')"has been removed.";
    }
};

Question #1: How do I exit from ForEach? I tried using "break" and "continue", but it doesn't work.

Question #2: I found that I can alter the list within a foreach loop... We can't do it like that in C#... Why does PowerShell allow us to do that?

解决方案

Item #1. Putting a break within the foreach loop does exit the loop, but it does not stop the pipeline. It sounds like you want something like this:

$todo=$project.PropertyGroup
foreach ($thing in $todo){
    if ($thing -eq 'some_condition'){
        break
    }
}

Item #2. PowerShell lets you modify an array within a foreach loop over that array, but those changes do not take effect until you exit the loop. Try running the code below for an example.

$a=1,2,3
foreach ($value in $a){
  Write-Host $value
}
Write-Host $a

I can't comment on why the authors of PowerShell allowed this, but most other scripting languages (Perl, Python and shell) allow similar constructs.

这篇关于如何从PowerShell中的ForEach-Object退出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-21 06:43