简体   繁体   English

Powershell | 导入.csv文件

[英]Powershell | Import .csv file

I want to import.csv file in Powershell.我想在Powershell中导入.csv文件。 It is only one line in the CSV, which is structured as follows: Text;Text;Text... CSV中只有一行,其结构如下: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'".我收到以下错误消息:“方法调用失败,因为 [System.IO.FileInfo] 不包含名为 'split' 的方法”。

Is there a better way to imort a csv file and safe each value in a seperate varibale?有没有更好的方法来保存 csv 文件并在单独的变量中保护每个值? Thanks for your help.谢谢你的帮助。

Your example file is not containing a header so I guess that's your problem.您的示例文件不包含 header 所以我想这是您的问题。 Then you need to specify it manually when Importing the CSV file.然后需要在导入 CSV 文件时手动指定。 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
$Header = 'Name','Age','Profession'
$data = Import-Csv -Path F:\Temp\NoHeader.csv -Delimiter ',' -Header $Header
$data | select Name, Age, Profession

在此处输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM