0

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.

4
  • Use the Import-CSV function instead: learn.microsoft.com/en-us/powershell/module/… Commented Jul 27, 2020 at 6:27
  • Hello, thanks for the comment. I have already tried that: Unfortunately it is not outputing anything when i try the following code: $Test = Import-Csv 'C:\Users\Win_User\Desktop\CSV-Files\2020-7-23 11-52-14.csv' -Delimiter ";" Write-Host $Test Commented Jul 27, 2020 at 6:36
  • Then you are doing it wrong, you should use Import-CSV. Thats the proper way to import a CSV file. If you update your question with example rows of the CSV I can probably give you a solution. Commented Jul 27, 2020 at 6:38
  • Hello in the. csv file are only 4 values it looks like this: 27.7.2020 08:43:33;User;PC-Name;Software-Name . Commented Jul 27, 2020 at 6:44

2 Answers 2

1

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
Sign up to request clarification or add additional context in comments.

Comments

0
$Header = 'Name','Age','Profession'
$data = Import-Csv -Path F:\Temp\NoHeader.csv -Delimiter ',' -Header $Header
$data | select Name, Age, Profession

enter image description here

Comments

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.