Search code examples
powershellcmdpathimport-csvstart-process

Need to Search an csv file and run an if/Where statement on the value to initialize a bat file


Want to clear my cache once the system memory usage exceeds 70% I have a task scheduler to start monitoring, a data collection for the performance log with report exported to csv, a custom event view to trigger the clearing, and a bat file to clear the cache.

This is the last piece to my puzzle.

Everything in cmd and powershell to my knowledge has been used

It has a header with three fields, and then 4 cells on information. (A2, B2, A3, B3)

powershell -command {Import-Csv -Path 'C:\PerfLogs\Admin\New Data Collector Set\Memory DataCollector01.csv' | Where{ $_.B3 -gt  "70.000000000000000"} | start-process $env:userprofile\Desktop\creatvent.bat}\

This is the performance report output in power shell and on notepad:

(PDH-CSV 4.0) (Eastern Daylight Time)(240) \\LT305-MIA\Memory\% Committed Bytes In Use Collect memory data usage percentage
------------------------------------------ ------------------------------------------- ------------------------------------  
08/19/2019 12:18:32.480                   41.363952528071579  
08/19/2019 12:19:32.467                   41.291049993897566


"(PDH-CSV 4.0) (Eastern Daylight Time)(240)","\\LT305-MIA\Memory\% Committed Bytes In Use","Collect memory data usage percentage"
"08/19/2019 15:38:37.582","47.54470529676059"," "
"08/19/2019 15:39:37.569","47.43784841788883"," "

I'd like to have this code work properly. Right know it runs everytime (no matter the value) i need it to run properly.


Solution

  • Since your file (as you show it) only has three columns with actual data and uses not really friendly headers, I suggest you do it like this:

    • Read the file as string array with Get-Content.
    • Skip the ugly header line
    • Convert the rest of the lines to CSV using custom headers
    • use a Where-Object clause to search for a value in the 2nd column that has a numeric greater than 70
    if (Get-Content -Path 'C:\PerfLogs\Admin\New Data Collector Set\Memory DataCollector01.csv' | 
        Select-Object -Skip 1 | 
        ConvertFrom-Csv -Header 'Date','MemoryUsage','DataUsage' | 
        Where-Object { [int]$_.MemoryUsage -gt 70 }) {
            # in here, run your .bat file to clear the cache
            Start-Process "$env:userprofile\Desktop\creatvent.bat"
    }