Perrypackettracer / Powershell-scripts-to-use-in-an-active-directory

0 stars 0 forks source link

Powershell script to monitor cpu usage and generates a daily report #7

Open Perrypackettracer opened 8 months ago

Perrypackettracer commented 8 months ago

To monitor server CPU usage and generate a daily report, you can use PowerShell along with the Get-Counter cmdlet to retrieve performance counter data. Below is a simple script that collects CPU usage information over a specified interval and creates a daily report in a CSV file.

# Set the server name and output file path
$ServerName = "YourServerName"
$OutputPath = "C:\Path\To\Reports\"

# Create a folder for reports if it doesn't exist
if (-not (Test-Path -Path $OutputPath)) {
    New-Item -ItemType Directory -Path $OutputPath
}

# Set the duration for monitoring (in seconds)
$MonitoringDuration = 3600  # 1 hour

# Generate a timestamp for the report
$Timestamp = Get-Date -Format "yyyyMMdd_HHmmss"
$ReportFileName = "CPU_Usage_Report_$Timestamp.csv"
$ReportFilePath = Join-Path -Path $OutputPath -ChildPath $ReportFileName

# Get CPU usage performance counter data
$CounterData = Get-Counter -ComputerName $ServerName -Counter "\Processor(_Total)\% Processor Time" -SampleInterval 2 -MaxSamples ($MonitoringDuration / 2)

# Create an array to store the data
$ReportData = @()

# Process counter data and populate the report array
foreach ($Sample in $CounterData.CounterSamples) {
    $ReportData += [PSCustomObject]@{
        Timestamp = $Sample.Timestamp
        CPUUsagePercent = $Sample.CookedValue
    }
}

# Export the report data to a CSV file
$ReportData | Export-Csv -Path $ReportFilePath -NoTypeInformation

Write-Host "CPU Usage Report generated: $ReportFilePath"

Explanation:

  1. Replace "YourServerName" with the actual name of the server you want to monitor.

  2. Set the $OutputPath variable to the desired directory where you want to save the reports.

  3. Adjust the $MonitoringDuration variable to set the duration for monitoring. In the example, it's set to 1 hour (3600 seconds).

  4. The script uses the \Processor(_Total)\% Processor Time performance counter to measure the total CPU usage.

  5. The script creates a CSV file with a timestamp in the filename, containing a timestamp and corresponding CPU usage percentage for each sample.

  6. Run this script daily using Task Scheduler to generate daily reports.

Remember to customize the script based on your specific needs and environment. Additionally, consider implementing error handling and logging for production use.