0

Thanks ahead of time. I'm trying to import multiple .csv files, add a column to them, then write to that column based on the value of another column

What I'm trying to do is follow this logic:

  • Loop through CSVs
  • For each CSV:
  • Add a new column
  • Look for some words.
  • If you see the words, write a different word in the new column
  • End loop
  • End loop

My code is here:

Function getTag ([string]$vuln){
   if($vuln -like "adobe-apsb-")
   {return "Adobe Flash"}
   if($vuln -like "jre-")
   {return "Java"}
   else
   {return "No vulnerability code available"}
}

$in = "D:\Splunk\Inbound"
$out = 'D:\Splunk\Outbound'
Get-ChildItem $in -Filter *.csv |
ForEach-Object{
    Import-Csv $_ | Select-Object *,@{Name='Tag';Expression={getTag $_.'Vulnerability ID'}} | Export-Csv $_.Name

}

Right now, $_ is coming through as a string, not a CSV, and I believe that's my problem. Does anyone have a good way to access that csv file from inside the nested loop?

3
  • Import-Csv $_.FullName? Commented Nov 15, 2016 at 17:33
  • It looks like you need to move the | export-csv to the end of your pipeline rather than put it inside of the loop. Commented Nov 15, 2016 at 17:44
  • Import-Csv $_.FullName solved it. Thanks everyone! Commented Dec 4, 2016 at 14:13

1 Answer 1

1
  • Your problem with using -like is a missing wildcard.
  • I guess the Outbound folder shall contain the modified csv?
  • These endless command lines aren't necessary, neither in a script nor in the shell.

For me this is much better readable (and it works) :

Function getTag ([string]$vuln){
    if ($vuln -like "adobe-apsb-*")
        {return "Adobe Flash"}
    if ($vuln -like "jre-*")
        {return "Java"}
    else
        {return "No vulnerability code available"}
}

$in  = "D:\Splunk\Inbound"
$out = "D:\Splunk\Outbound\"

Get-ChildItem $in -Filter *.csv |
    ForEach-Object{
        Import-Csv $_.FullName | 
            Select-Object *,@{
                Name='Tag';
                Expression={getTag $_.'Vulnerability ID'}
            } | Export-Csv -path $($out+$_.Name) -notype
    } 
> tree . /f
│
├───Inbound
│       test.csv
│
└───Outbound
        test.csv

> gc .\Inbound\test.csv
"A","Vulnerability ID","C"
0,"adobe-apsb-blah",2
5,"jre-trash",9

> gc .\Outbound\test.csv
"A","Vulnerability ID","C","Tag"
"0","adobe-apsb-blah","2","Adobe Flash"
"5","jre-trash","9","Java"
Sign up to request clarification or add additional context in comments.

2 Comments

What language is that?
The upper part is the same powershell, the lower is simply a console screen copy.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.