Quantcast
Channel: PowerShell.com – PowerShell Scripts, Tips, Forums, and Resources
Viewing all articles
Browse latest Browse all 8583

Need help with reading dynamic columns from csv file

$
0
0

Hello,

I am trying to write a script which will accept dynamic columns. Currently, I am using a discrete number of columns specifying the element number. What I ultimately want is to be able to run the script on various csv files. The example I have now have 20 columns, I want to be able to run a script that has 64, 12, 45, any number. Please help! 

 

$psobject = Import-Csv -Path "C:\BI csv samples\sample.csv"

[string]$DateFieldName = "Date"

foreach($row in $psobject)

{

    $line = ""

    $line = [string]::Format("{0}="+"{1}","Date" , $row."$DateFieldName")   

    foreach($field in ($psobject|gm| ? { $_.membertype -eq "noteproperty"} ).name)

    {

        if ("$field" -ne "$DateFieldName")

        {

              $line = [string]::Format("{0}"+"{2}", $line,$field -replace " ", $row."$field")  

   $line += ([Environment]::NewLine)

foreach($field in ($psobject|gm| ? { $_.membertype -eq "noteproperty"} )[0].name)

               {

   $line = [string]::Format("{0}"+"{1}=""{2}""", $line,$field -replace " ", $row."$field")   

   $line += ([Environment]::NewLine)

foreach($field in ($psobject|gm| ? { $_.membertype -eq "noteproperty"} )[1].name)

               {

   $line = [string]::Format("{0}"+"{1}=""{2}""", $line,$field -replace " ", $row."$field")   

   $line += ([Environment]::NewLine)

foreach($field in ($psobject|gm| ? { $_.membertype -eq "noteproperty"} )[2].name)

                {

   $line = [string]::Format("{0}"+"{1}=""{2}""", $line,$field -replace " ", $row."$field")   

   $line += ([Environment]::NewLine)

foreach($field in ($psobject|gm| ? { $_.membertype -eq "noteproperty"} )[3].name)

                 {

$line = [string]::Format("{0}"+"{1}=""{2}""", $line,$field -replace " ", $row."$field")   

   $line += ([Environment]::NewLine)

                 }

         }

    }

}

$line += ([Environment]::NewLine)

    Add-Content  "C:\BI csv samples\sampleSplunkyOutput.txt" "$line"

  }

 }

}


Viewing all articles
Browse latest Browse all 8583

Trending Articles