Below is the script I developed to measure CPU speed and write output to log file. I need a small help in scripting. I need to schedule this script when an application is launched and need to stop this script from writing to log immediately after quitting the launched application. How do I handle that in this script? Pls assist
# Initialising the variables
$Array = @()
$Server = (Get-ComputerInfo).CsName
$measurecmd = (measure-command { 1..1000 | % {random} | sort }).Seconds
$datetime = Get-Date
$sortsec = "1000"
$LogTime = Get-Date -Format "MM-dd-yyyy_hh-mm-ss"
$LogFile = 'C:\Avanthi\PS_script_'+$LogTime+".log"
# Starting the timer to iterate the output till session is closed
$timer = [Diagnostics.Stopwatch]::StartNew()
while ($timer.Elapsed.TotalSeconds -lt 1800) {
Try {
# Processor utilization
$Processor = (Get-WmiObject -ComputerName $Server -Class win32_processor -ErrorAction Stop | Measure-Object -Property LoadPercentage -Average | Select-Object Average).Average
# Memory utilization
$ComputerMemory = Get-WmiObject -ComputerName $Server -Class win32_operatingsystem -ErrorAction Stop
$Memory = ((($ComputerMemory.TotalVisibleMemorySize - $ComputerMemory.FreePhysicalMemory)*100)/ $ComputerMemory.TotalVisibleMemorySize)
$RoundMemory = [math]::Round($Memory, 2)
# Creating custom object
# MachineName Date Time sort100kseconds
$Object = New-Object PSCustomObject
$Object | Add-Member -MemberType NoteProperty -Name "Server name" -Value $Server
$datetime = Get-Date
$Object | Add-Member -MemberType NoteProperty -Name "Date Time" -Value $datetime
$Object | Add-Member -MemberType NoteProperty -Name "CPU %" -Value $Processor
$Object | Add-Member -MemberType NoteProperty -Name "Memory %" -Value $RoundMemory
$Object | Add-Member -MemberType NoteProperty -Name "Meaure CPU speed" -Value (measure-command { 1..1000 | % {random} | sort }).Seconds
$Object | Add-Member -MemberType NoteProperty -Name "Sort Seconds" -Value $sortsec
$Object
$Array += $Object
}
Catch {
Write-Host "Something went wrong ($Server): "$_.Exception.Message
Continue
}
#Final results - Writing to Log file
If ($Array) {
$Array | Out-File $LogFile -Force
}
# Sleep for amount of seconds
Start-Sleep -Seconds 60
}