使用powershell从csv文件中读取数据并对数组

时间:2017-09-18 19:26:10

标签: powershell csv row

#My script is as below 
$empdata = import-csv Log.csv
    ForEach ($Item in $empdata){
    "FirstName = $($empdata.FirstName)
    LastName = $($empdata.LastName)
    Laptop = $($empdata.Laptop)
    AccessCard = $($empdata.AccessCard)
    Phone = $($empdata.Phone)
    Building = $($empdata.Building)
    Location = $($empdata.Location)"
    Write-host $FirstName $LastName $Laptop  $AccessCard $Phone $Building 
    $Location

我想将每行的数据读入数组并将其传递给另一个工具,但由于我将所有列的数据放在一起,所以无法这样做,例如第1列的所有数据都会出现..

结果如下

FirstName = Suresh Krishna Shiva
LastName = setty Murthy Reddy
Laptop = Lenovo Lenovo Hp
AccessCard = yes No Yes
Phone = 123456789 45678932 12378945
Building = T4 P1 DT14
Location = Chennai Bangalore Hyderabad
FirstName = Suresh Krishna Shiva
LastName = setty Murthy Reddy
Laptop = Lenovo Lenovo Hp
AccessCard = yes No Yes
Phone = 123456789 45678932 12378945
Building = T4 P1 DT14
Location = Chennai Bangalore Hyderabad
FirstName = Suresh Krishna Shiva
LastName = setty Murthy Reddy
Laptop = Lenovo Lenovo Hp
AccessCard = yes No Yes
Phone = 123456789 45678932 12378945
Building = T4 P1 DT14
Location = Chennai Bangalore Hyderabad

I  am trying to get data in the below format


FirstName = Suresh
LastName = setty
Laptop = Lenovo
AccessCard = yes
Phone = 123456789
Building = T4
Location = Chennai    

3 个答案:

答案 0 :(得分:0)

$empdata = Import-Csv Log.csv

foreach ($item in $empdata) {
    "FirstName = $($item.FirstName)
    LastName = $($item.LastName)
    Laptop = $($item.Laptop)
    AccessCard = $($item.AccessCard)
    Phone = $($item.Phone)
    Building = $($item.Building)
    Location = $($item.Location)"
}

$empdata.FirstName =整个FirstName列(所有行)

$item.FirstName = foreach迭代中当前行的FirstName

$FirstName $LastName $Laptop $AccessCard $Phone $Building $Location:在您的示例中,这些都是null(并且不需要生成您想要的输出)

答案 1 :(得分:0)

#classiq method
import-csv "c:\temp\test.csv" | %{
   "FirstName=$($_.FirstName)"
   "LastName=$($_.LastName)"
   "Phone=$($_.Phone)"
}

#other method with format
import-csv "c:\temp\test.csv" | %{
   "FirstName={0}`nLastName={1}`nPhone={2}" -f $_.FirstName, $_.LastName, $_.Phone
}

答案 2 :(得分:0)

Import-Csv .\Log.csv | ForEach-Object{

    "
        FirstName= $($_.FirstName) `n
        LastName= $($_.LastName)   `n
        Laptop= $($_.Laptop)       `n
        AcessCard= $($_.AcessCard) `n
        Phone= $($_.Phone)         `n
        Building= $($_.Building)   `n
        Location= $($_.Location)
    "
}