【问题标题】:PowerShell - Csv : foreach with conditions?PowerShell - Csv:foreach 有条件?
【发布时间】:2013-06-28 07:37:27
【问题描述】:

我要导入一个csv文件,我想直接在foreach中放一个条件。 我的意思是:

要读取 csv,我会(是的,我的分隔符是 \ ):

$csv = Import-Csv -Delimiter \ -Path $mypath -Header 'column1', 'column2', 'column3'

然后我做:

foreach($line in $csv)
{
#Actions
}

我想做什么,但我不知道是否可行:

for($i =1; $i -lt $myarray.Length; $i++)
{
   foreach($line in $csv) | Where $line.column2 -eq $myarray[$i]
   {
      #Actions only if $line.column2 is equal to $myarray[$i]
   }
}

所以我得到了一个数组,里面有名字。而且我想做#Actions,只有当csv中的一列与我的数组中的信息匹配时。如果没有,我想在 $csv 中更改 $line。

我写的想法看起来很沉重,我认为有更好更快(更难更强大#DaftPunk)的方法来做到这一点。

如果有人以前用过这个,请告诉我:)

提前致谢,

尼科。

P.S : 我为我的英语道歉 ;)

编辑:我刚刚意识到我可以做一个 if 条件:

for($i =1; $i -lt $myarray.Length; $i++)
{
   foreach($line in $csv)
   {
      if($line.column2 -eq $myarray[$i]
      {
         #Actions
      }
   }
}

但我仍然认为:| #Conditions 在哪里更好...

【问题讨论】:

    标签: loops powershell foreach conditional-statements


    【解决方案1】:

    你可以在循环中使用 IF,这是一个通用的方法

    Import-Csv ... | Foreach-Object{
    
       if(something)
       {
          #do something with the current object and write it back to the pipeline
          $_ = ...
          $_
       }
       else
       {
          # write the object back to the pipeline
          $_
       }
    }
    

    【讨论】:

    • 谢谢 :) 我会用这个。谢谢。
    • 是的,**if ($.HeaderName -eq desiredValue) {} 有效,或者 where-object 也可以。
    猜你喜欢
    • 1970-01-01
    • 2017-01-20
    • 1970-01-01
    • 1970-01-01
    • 2012-05-31
    • 2018-07-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多