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

0 stars 0 forks source link

Script to monitor Memory usage and create dailly reports #8

Open Perrypackettracer opened 8 months ago

Perrypackettracer commented 8 months ago

Below is a PowerShell script that monitors memory usage on a server and generates a daily report. It utilizes the Get-Counter cmdlet to retrieve performance counter data for memory usage.

# 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 = "Memory_Usage_Report_$Timestamp.csv"
$ReportFilePath = Join-Path -Path $OutputPath -ChildPath $ReportFileName

# Get memory usage performance counter data
$CounterData = Get-Counter -ComputerName $ServerName -Counter "\Memory\Available MBytes", "\Memory\Committed Bytes", "\Memory\% Committed Bytes In Use" -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
        AvailableMemoryMB = $Sample.CounterSamples[0].CookedValue
        CommittedBytes = $Sample.CounterSamples[1].CookedValue
        CommittedBytesInUsePercent = $Sample.CounterSamples[2].CookedValue
    }
}

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

Write-Host "Memory 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 three performance counters to measure memory usage: Available Memory (MB), Committed Bytes, and % Committed Bytes In Use.

  5. The script creates a CSV file with a timestamp in the filename, containing data on available memory, committed bytes, and the percentage of committed bytes in use for each sample.

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

Customize the script based on your specific needs and environment, and consider implementing error handling and logging for production use.