Reputation: 85
I have a file containing a list of jobs. I need to run through that file in a foreach loop and for each value I need to look for that in the first column of an array then check the value in the 3rd column and if that is N output the jobname.
So far I have,
$header = 1..4 | ForEach-Object { "h$_" }
$data = Get-Content F:\temp\Connect_Project\connect_jobs.txt
$data2 = "F:\temp\Connect_Project\alljobs.csv" |
Import-Csv -Delimiter ',' -Header $header
$stream = [System.IO.StreamWriter] "F:\temp\Connect_Project\jobs_to_change.txt"
foreach ( $line in $data ) {
if ( $data2.h1 -match $line ) {
if ( $data2.h3 -match 'N' ) {
$stream.WriteLine($line)
}}}
$stream.Close()
I know that's not working (although it is removing jobs that don't exist in the array) but I'm struggling to work out how to fix it.
Can anyone help?
To update based on comments,
I've also tried
$header = 1..4 | ForEach-Object { "h$_" }
$data = Get-Content F:\temp\Connect_Project\connect_jobs.txt
$data2 = "F:\temp\Connect_Project\alljobs.csv" |
Import-Csv -Delimiter ',' -Header $header
$stream = [System.IO.StreamWriter] "F:\temp\Connect_Project\jobs_to_change.txt"
foreach ( $line in $data ) {
$state = ($data2 | Where-Object {$_.h1 -match $file} | Select-Object h3)c
$line
$state
if ( $state = 'N') {
$stream.WriteLine($line)
}}
$stream.Close()
I can see that I'm matching h1 but I'm getting all h3 values not just the one I want.
Upvotes: 0
Views: 1482
Reputation: 85
Well that was obvious once I spotted it. Thanks to EBGreen for the where-object tip. Second version worked once I realised I'd put $file in the match and not $line. Corrected it to $line and it's doing what I wanted.
$header = 1..4 | ForEach-Object { "h$_" }
$data = Get-Content F:\temp\Connect_Project\connect_jobs.txt
$data2 = "F:\temp\Connect_Project\alljobs.csv" |
Import-Csv -Delimiter ',' -Header $header
$stream = [System.IO.StreamWriter] "F:\temp\Connect_Project\jobs_to_change.txt"
foreach ( $line in $data ) {
$state = $data2 | Where-Object {$_.h1 -match $line} | Select-Object h3
if ( $state -match 'N') {
$stream.WriteLine($line)
}}
$stream.Close()
Upvotes: 1