0
votes

I'm new to PowerShell and I'm trying to write a script that will help me parse large amounts of user session statistics. I have 2 CSVs:

currentmonth.csv

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

... and ...

previousmonth.csv

UserName;Hours
User1;2
User2;100

I want to compare currentmonth.csv against previousmonth.csv and if an user (ex. User3) is not present in CSV for the previous month, give value for hours as "0" and save the processed data in a new CSV (ex. parsedmonth.csv).

Desired output:

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

What would be the simplest way to achieve this?

1

1 Answers

0
votes

Try something like this:

# 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