简体   繁体   English

加速 CSV Powershell 脚本

[英]Speed up CSV Powershell script

I've got a Powershell script that functions but it takes ages to complete.我有一个 Powershell 脚本可以运行,但需要很长时间才能完成。 I'm a newbie with Powershell and i can't find a solution to speed up the proces.我是 Powershell 的新手,我找不到加快进程的解决方案。 Hopefully somebody can show me to the right direction.希望有人能告诉我正确的方向。

Example.例子。 I've got 2 csv files.我有 2 个 csv 文件。

CSV 1: CSV 1:

CI Name,Last Logon Account
Computer1, User1
Computer2, User2
Computer3, User3

CSV 2: CSV 2:

Device Display Label,Subscriber Employee Id
Computer1, User1
Computer2, User2
Computer3, User6

I want to have all the Ci names in the first column with the last logon account in the second column and match subscriber employee id with ci name from the first file.我想将第一列中的所有 Ci 名称与第二列中的最后一个登录帐户相匹配,并将订阅者员工 ID 与第一个文件中的 ci 名称匹配。

Resulting in:导致:

Ci name, Last logon Account, Subscriber Employee Id
Computer1,User1,User1
Computer2,User2,User2
Computer3,User3,User6

I have the following script in Powershell:我在 Powershell 中有以下脚本:

$Data = Import-csv 'C:\Temp\Excel\CSV\file1.csv'   
$Data2 = Import-Csv 'C:\Temp\Excel\CSV\file2.csv' 
$combine = @() 

foreach ($first in $Data) {
  foreach ($second in $Data2) {
    if ($second.'Device Display Label' -eq $first.'CI Name') {
        $match = New-Object PSObject
        $match | Add-Member Noteproperty "Ci Name" $first.'CI Name'
        $match | Add-Member Noteproperty "Last Logon Account" $first.'Last Logon Account'
        $match | Add-Member Noteproperty "Subscriber Employee Id" $second.'Subscriber Employee Id'
        $combine += $match
    }
  }
}
$Combine

It works and it gives the desired result.它有效,并给出了预期的结果。

The only problem is that both csv files have 15000 lines.唯一的问题是两个 csv 文件都有 15000 行。 So it takes ages to finish the script.所以完成剧本需要很长时间。 Is there a way to speed up the proces.有没有办法加快进程。 I hope somebody can point me to the right direction.我希望有人能指出我正确的方向。

Use a hashtable to build an index out of one of the CSV files - this way you don't need the nested loops and the runtime should drop significantly:使用哈希表从 CSV 文件之一构建索引 - 这样您就不需要嵌套循环并且运行时应该显着下降:

# Build index/reference table from first data set
$DataTable = @{}
Import-csv 'C:\Temp\Excel\CSV\file1.csv' |ForEach-Object {
  $DataTable[$_.'CI Name'] = $_
}

# No need to store the second data set in an intermediate variable
$combine = Import-Csv 'C:\Temp\Excel\CSV\file2.csv' |ForEach-Object {
  if($DataTable.ContainsKey($_.'Device Display Label')){
    # Take the existing object from the first data set 
    # and add the subscriber from the second data set
    $DataTable[$_.'Device Display Label'] |Add-Member NoteProperty "Subscriber Employee Id" $_.'Subscriber Employee Id' -PassThru
  }
}

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

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