Export array (table) into csv-file in Powershell

In your work in big arrays of data in Powershell, very often you will need to export data to table and after open this table in Excel. Its not recommended to code direct export from array into Excel-file, because you will need Excel installed on computer where you run the script. Also, such a code will run slowly.
So, I've decided to export data to csv-file.
How we can do that?

First of all, we need to define the array:
$export_array = @();

Then, fill in the data you need:

$export_array += ,@(""); # just an empty string
$export_array += ,@($a1, $b1, $c1);
$export_array += ,@($a2, $b2, $c2);
$export_array += ,@($a3, $b3, $c3);

Compose csv file name and path to it:

$datetime = Get-Date -Format "yyyy.MM.dd_HH-mm-ss";
$file_name = "audit_result_" + $datetime + ".csv";
$file_path = "./" + $file_name;

Actual export of array into csv-file:

foreach($item1 in $export_array)  
  $csv_string = "";
  foreach($item in $item1)
    $csv_string = $csv_string + $item + ";";
  Add-Content $file_path $csv_string;

Tags: script, powershell (ru)


Add comment

Security code