I want to get the CPU and memory stats of a process and want to add it in the CSV at regular intervals. Following is the powershell script I wrote for that:
# Specify the process names
$process1Name = "abcd"
$csvFilePath = "C:\Users\johndoe\Stats.csv"
# Create an array to store process stats
$processStats = @()
# Loop to monitor processes every second
$exportIntervalInSeconds = 60 # Set the desired export interval
$iterationCount = 0
# Function to get CPU and Memory usage of a process
function Get-ProcessStats {
param (
[string]$processName
)
$process = Get-Process -Name $processName -ErrorAction SilentlyContinue
if ($process -ne $null) {
$cpuUsage = $process.CPU
$memoryUsage = $process.WorkingSet64
Write-Output "$processName - CPU Usage: $cpuUsage%, Memory Usage: $memoryUsage bytes"
# Create an object with process stats
$statsObject = [PSCustomObject]@{
ProcessName = $processName
CPUUsage = $cpuUsage
MemoryUsage = $memoryUsage
}
Write-Output "Stats: $statsObject"
# Add the stats object to the array
$processStats += $statsObject
Write-Output "ProcessStats:"
$processStats | Format-Table
$processStats.Count
} else {
Write-Output "$processName not found."
}
}
# Loop to monitor processes every second
while ($true) {
Get-ProcessStats -processName $process1Name
Start-Sleep -Seconds 1
$iterationCount++
# Clear-Host # Optional: Clear the console for better readability
if ($iterationCount -ge $exportIntervalInSeconds) {
# Export the process stats to CSV
Write-Output "Reached the iteration count greater than export interval"
Write-Output "Exporting process stats to CSV:"
$processStats | Format-Table
Write-Output "Exporting..."
$processStats | Export-Csv -Force -Path $csvFilePath -NoTypeInformation
# Reset iteration count
$iterationCount = 0
$processStats = @()
}
}
I dont see anything getting added in Stats.csv after regular intervals. In fact, the processStats does not contain anything. Interesting thing is the value of statsObject gets printed and the processStats value in the function Get-ProcessStats also gets printed but contains only 1 value at that moment. Not sure what is going wrong and why all the values are not getting printed and stored in CSV file.
Start-Sleep, what is in the global array variable$processStats?