Reputation: 251
I have to import a csv file, and I want to put a condition directly in the foreach. I mean :
To read the csv, i do (yes my delimiter is \ ) :
$csv = Import-Csv -Delimiter \ -Path $mypath -Header 'column1', 'column2', 'column3'
Then i do :
foreach($line in $csv)
{
#Actions
}
What i would like to do, but I din't know if it's possible :
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]
}
}
So i got an array, with names inside. And I want to do #Actions, only if a column in the csv, match to the information in my array. If not, I want to change of $line in $csv.
The idea i wrote looks so heavy, and I think there is a better and faster (harder and stronger #DaftPunk) way to do this.
If someone has already use this before, let me know :)
Thanks in advance,
Nico.
P.S : I apologize for my english ;)
EDIT : I've just realized that i can do a if condition :
for($i =1; $i -lt $myarray.Length; $i++)
{
foreach($line in $csv)
{
if($line.column2 -eq $myarray[$i]
{
#Actions
}
}
}
But i still think that a : | Where #Conditions, is better ...
Upvotes: 0
Views: 7317
Reputation: 126732
You can use IF inside the loop, here's a general approach
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
$_
}
}
Upvotes: 1