简体   繁体   English

在PowerShell中使用多个工作表从.CSV读取数据

[英]Read data from .CSV with multiple worksheets in PowerShell

This is my code: 这是我的代码:

$Process = @()
$Energy = @()

Import-Csv C:\Users\Shuai\Desktop\test\Test.csv |`
ForEach-Object {
                $Process += $_."Process"
                $Energy += $_.Energy
               }

$inputName = Read-Host -Prompt "Process"

if ($Process -contains $inputName)
               {
                 Write-Host "Customer Exists!"
                 $Where = [array]::IndexOf($Process, $inputName)
                 $Energy[$Where]
               }

I use this code to read data from the .CSV. 我使用此代码从.CSV读取数据。 Currently, there is only one worksheet. 当前,只有一个工作表。 I want to add another worksheet with a new table in the same file. 我想在同一文件中添加另一个带有新表的工作表。 How to read data from this new worksheet without affecting the first one? 如何在不影响第一个工作表的情况下从此新工作表中读取数据? Do I need to make variables for both of the worksheets? 我是否需要为两个工作表都做变量? What code should I use for this? 我应该为此使用什么代码?

First of all, there's no need to put your values into separate arrays. 首先,不需要将值放入单独的数组中。 In fact, keeping the data in the model provided by Import-Csv makes your job easier: 实际上,将数据保留在Import-Csv提供的模型中可以使您的工作更加轻松:

$ProcessSheet = Import-Csv C:\Users\Shuai\Desktop\test\Test.csv
$inputName = Read-Host -Prompt "Process"

$Process = $ProcessSheet |Where-Object {$_.Process -eq $inputName}
if ($Process)
{
    Write-Host "Customer Exists!"
    $Process
}

A CSV -file is very simple format, essentially representing the data set found in a single sheet . CSV文件是一种非常简单的格式,本质上表示在一张纸上找到的数据集。

So, if you want a separate table, use a separate file! 因此,如果要使用单独的表,请使用单独的文件!

$ProcessSheet = Import-Csv C:\Users\Shuai\Desktop\test\Test.csv
$inputName = Read-Host -Prompt "Process"

$Process = $ProcessSheet |Where-Object {$_.Process -eq $inputName}
if ($Process)
{
    Write-Host "Customer Exists!"
    $Process
}

# New sheet? New variable!
$ServiceSheet = Import-Csv C:\Users\Shuai\Desktop\test\Test2.csv
$inputName = Read-Host -Prompt "Service"

$Service = $ServiceSheet |Where-Object {$_.Service -eq $inputName}
if($Service){
    Write-Host "Service Exists!"
    $Service
}

If you want to store multiple sheets in the same file, you would have to use Excel. 如果要在同一文件中存储多个图纸,则必须使用Excel。

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

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