【问题标题】:PowerShell: How to compare 2 CSVs and export desired results to a new CSV?PowerShell:如何比较 2 个 CSV 并将所需结果导出到新的 CSV?
【发布时间】:2020-06-02 12:18:02
【问题描述】:

我是 PowerShell 的新手,我正在尝试编写一个脚本来帮助我解析大量用户会话统计信息。我有 2 个 CSV:

currentmonth.csv

UserName;Hours
User1;0,5
User2;120
User3;1

...和...

previousmonth.csv

UserName;Hours
User1;2
User2;100

我想将 currentmonth.csvpreviousmonth.csv 进行比较,如果用户(例如 User3不是 在 CSV 中显示上个月,将小时值指定为“0”并将处理后的数据保存在新的 CSV 中(例如 parsedmonth.csv)。

期望的输出:

UserName;Hours
User1;0,5
User2;120
User3;0

实现这一目标的最简单方法是什么?

【问题讨论】:

    标签: powershell csv


    【解决方案1】:

    试试这样的:

    # Load the 2 CSV files
    $currentmonth = import-csv .\currentmonth.csv -delimiter ';'
    $previousmonth = import-csv .\previousmonth.csv -delimiter ';'
    
    # Variable to hold output
    $op = @()
    
    foreach($entry in $currentmonth)
    {
        # Loop through all entries in the current month and check against previous month
        if($previousmonth.username -contains $entry.username)
        {
            # If found, add the entry to the output variable
            $op += $entry
        }
        else
        {
            # If not found, create a temp object to hold values and add to output variable
            $tmp = new-object object
            $tmp | add-member -type noteproperty -name UserName $entry.UserName
            $tmp | add-member -type noteproperty -name Hours 0
            $op += $tmp
        }
    }
    
    # Write output variable to CSV file
    $op | export-csv .\monthcheckresults.csv -notype
    

    【讨论】:

    • 谢谢,这会产生我想要的结果!
    猜你喜欢
    • 2022-01-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-10
    • 2014-12-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多