I've been tasked with using Powershell to count the number of occurrences where a particular action occurs in an application on a remote system. The count of actions is already being put into a CSV file every 30 minutes, each file overwriting the previous one, though I can make a copy of the file to act as the "old" version. The number of rows never exceeds 100-200 rows. I believe the logic would be:
- Every 30 minutes, import both the old and new CSV files.
- Cycle through each row in the new CSV file and determine if there is a matching value in the "Action" column of the old CSV file.
- If a matching value is found, add the "Count" field from the new CSV file to the "Count" field in the old CSV file in the row matching the "Action" field.
- If no matching value is found, append the "Count" and "Action" fields to the end of the old CSV file.
For example, the "new file" should be added to the "old file in its original form" to equal the "old file after update".
*I've tried multiple times to post an example, but even though the formatting is showing that I've got it correct when I review the post, when it's actually posted, it gets all messed up - hopefully the logic I laid out before is enough. Here's just a Notepad paste (which I know looks terrible; I'm not quite sure how to get it formatted properly):
New file Count Action 6 Apples 5561 Oranges 5 Bananas 324 Kiwis 8 Grapefruits
Old file in its original form: Count Action 14 Apples 1 Pomegranate 5205 Oranges 491 Kiwis 1 Grapefruits
Old file after update: Count Action 20 Apples 1 Pomegranate 10766 Oranges 5 Bananas 815 Kiwis 9 Grapefruits *
The code I have is still very bare-bones; I can see what needs to happen, but I'm having trouble wrapping my head around exactly how to get Powershell to perform the work. Looks like I picked a bad week to switch to decaf.
# Define the script's name and location, move to that location
$scriptPath = split-path -parent $MyInvocation.MyCommand.Definition
$CurrentLocalFolder = "$scriptPath"
Set-Location -Path $CurrentLocalFolder
# Define file names and locations
$OriginalCSVFilename = "ActionReport_Count.csv"
$OriginalCSVFilepath = $CurrentLocalFolder + "\Output\" + $OriginalCSVFilename
$OriginalCSVFilepath = $OriginalCSVFilepath.ToString()
$NewCSVFilename = "ActionReport_Count_New.csv"
$NewCSVFilepath = $CurrentLocalFolder + "\Output\" + $NewCSVFilename
$NewCSVFilepath = $NewCSVFilepath.ToString()
# Import files
$OriginalCSVFile = Import-CSV -Path $OriginalCSVFilepath -Delimiter ","
$NewCSVFile = Import-CSV -Path $NewCSVFilepath -Delimiter ","
# Perform comparisons to know which fields to add to
ForEach ($NewRow in $NewCSVFile) {
ForEach ($OldRow in $OriginalCSVFile) {
If ($NewRow.Name -eq $OldRow.Name) {
# Some kind of magic happens here
}
}
}
Any help would be greatly appreciated!!!