Search code examples
powershellcsvimport-csv

Powershell | Import .csv file


I want to import .csv file in Powershell. It is only one line in the CSV, which is structured as follows: Text;Text;Text...

This is what i have tried before:

$folder_csv = 'C:\Users\Win_User\Desktop\Folder\CSV_Files'
$files = Get-ChildItem $folder_csv -File -Filter *.csv

foreach ($file in $files) {

                    $Split_content = $file.split(";")
    
                    $timestamp = $($Split_content[0])
                    $User = $($Split_content[1])
                    $PC = $($Split_content[2])
                    $Software = $($Split_content[3]).Substring(1)
                    }
Write-Host $timestamp + " " + $User + " " + $PC + " " + $Software

I get the following Error Message: "Method invocation failed because [System.IO.FileInfo] does not contain a method named 'split'" .

Is there a better way to imort a csv file and safe each value in a seperate varibale? Thanks for your help.


Solution

  • Your example file is not containing a header so I guess that's your problem. Then you need to specify it manually when Importing the CSV file. This code works only for when you have one row, if you have multiple rows it will just overwrite the variables and keep the last one. But feel free to change that.

    $Header = 'timestamp','User','PC','Software'
    
    $data = Import-Csv -Path .\testcsv.csv -Delimiter ';' -Header $Header
    
    
    
    foreach ($row in $data) {
       
        $timestamp = $row.timestamp
        $User = $row.User
        $PC = $row.PC
        $Software = $row.Software
    }
    
    $timestamp
    $User
    $PC
    $Software