$currentPath = Split-Path -Parent $MyInvocation.MyCommand.Definition;
#Write-Output $currentPath
Write-Output “$currentPath\commonFunctions.ps1”
import-module “$currentPath\commonFunctions.ps1”
<#
function writeLog($str)
{
write-host($str)
$logStr = “$( Get-Date ) $scenarioName - $str”
Add-content $logfile -value $logStr
}
function sendApiRequest()
{
$jsonData = $jsonData.Substring(0, ($jsonData.Length - 1));
$jsonData = ‘[’ + $jsonData + ‘]’;
$fullUrl = $apiServer + $environment.toLower()
write-host $fullUrl
$credentials = [System.Convert]::ToBase64String([System.Text.Encoding]::ASCII.GetBytes("$( $apiUser ):$( $apiPassword )"))
$headers = @{
Authorization = "Basic $credentials"
}
writeLog ("SENDING DATA: $jsonData");
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
$response = Invoke-WebRequest -Uri $fullUrl -Method POST -Headers $headers -Body $jsonData -ContentType "application/json"
writeLog ("DATA: $response");
}
#>
…
$scenarioName = $MyInvocation.MyCommand.Name
$scenarioName = $scenarioName.Substring(0,$scenarioName.LastIndexOf(‘.’))
$configFile = “D:\apps\scheduledtasks\dashboard$scenarioName.xml”
$logfile = “D:\apps\scheduledtasks\dashboard$scenarioName.log”
try
{
$xml = [xml](Get-Content $configFile)
$apiServer = $xml.CONFIG.API_SERVER
#using decoding functionality
$apiUser = decoding -encoded $xml.CONFIG.API_USER
$apiPassword = decoding -encoded $xml.CONFIG.API_PASS
$environment = $xml.CONFIG.ENVIRONMENT
$servers = $xml.CONFIG.SERVERS.SERVER
$maxCpu = $xml.CONFIG.THRESHOLD_CPU
$maxRam = $xml.CONFIG.THRESHOLD_RAM
$maxDisk = $xml.CONFIG.THRESHOLD_DISK
$maxNetwork = $xml.CONFIG.THRESHOLD_NETWORK
$maxSwap = $xml.CONFIG.THRESHOLD_SWAP
$maxThreads = $xml.CONFIG.THRESHOLD_THREADS
$eventId = $xml.CONFIG.EVENTID
}
catch
{
writeLog (“ERROR: XML $scenarioName.xml File was not found. Error: $Error[0]”);
}
writeLog (" ");
writeLog (“INFO: Running job”);
$jsonData = ‘’;
$jsonData += ‘{“chart”:“hwCpu”, “name”:“threshold”, “value”:’ + $maxCpu + '}, ';
$jsonData += ‘{“chart”:“hwRam”, “name”:“threshold”, “value”:’ + $maxRam + '}, ';
$jsonData += ‘{“chart”:“hwDisk”, “name”:“threshold”, “value”:’ + $maxDisk + '}, ';
$jsonData += ‘{“chart”:“hwNetwork”, “name”:“threshold”, “value”:’ + $maxNetwork + '}, ';
$jsonData += ‘{“chart”:“hwSwap”, “name”:“threshold”, “value”:’ + $maxSwap + '}, ';
$jsonData += ‘{“chart”:“hwThreads”, “name”:“threshold”, “value”:’ + $maxThreads + '}, ';
foreach ($server in $servers)
{
write-host “Checking server $server”
# CPU
$jsonData += Invoke-Command -ComputerName $server -ScriptBlock {
Get-WmiObject Win32_Processor | Measure-Object -Property LoadPercentage -Average | Select-Object Average |
Foreach-Object {
# write-host ("Max CPU 1",$($using:maxCpu))
$usedCpu=[math]::Round($_.Average, 0)
write-host ("CPU consumption", $usedCpu)
function monitoringCreateEventViewerEntry($errorResult)
{
if ($errorResult.length -gt 0)
{
try
{
$errorResult = "CODE: $($using:scenarioName) `r`nDESCRIPTION: " + $errorResult
Write-EventLog -LogName "Application" -Source "SQLSERVERAGENT" -EventID $using:eventId -EntryType Error -Message $errorResult
}
catch
{
write-host("Creating SQLSERVERAGENT Source in EventViewer")
[System.Diagnostics.EventLog]::CreateEventSource("SQLSERVERAGENT", "Application")
}
}
}
$maxCpu = [double]$($using:maxCpu) #deepthi
<#
write-host ("---------------------------------------------------------------")
$typeOfVar = $usedCpu.GetType()
write-host ("---------------->usedCpu = $usedCpu, $typeOfVar" )
$typeOfVar = $maxCpu.GetType()
write-host ("---------------->maxCpu = $maxCpu, $typeOfVar" )
write-host ("---------------------------------------------------------------")
#>
#if ( $usedCpu -gt $($using:maxCpu))
if ( $usedCpu -gt $maxCpu)
{
write-host ("Exceed the threshold limit of CPU consumption");
$eventData = ("CPU exceeded threshold for : " + $env:COMPUTERNAME.ToLower() + " CPU threshold: " + $using:maxCpu + " actual CPU usage: " + $usedCpu)
monitoringCreateEventViewerEntry($eventData)
}
return ('{"chart":"hwCpu", "name":"' + $env:COMPUTERNAME.ToLower() + '", "value":"' + $usedCpu + '"},')
}
}
# RAM
$jsonData += Invoke-Command -ComputerName $server -ScriptBlock {
$system = Get-WmiObject win32_OperatingSystem
$totalRam = $system.TotalVisibleMemorySize
$freeRam = $system.FreePhysicalMemory
$usedRamPerc = [math]::Round((($totalRam - $freeRam) / $totalRam) * 100, 0)
write-host ("RAM consumption",$usedRamPerc);
function monitoringCreateEventViewerEntry($errorResult)
{
if ($errorResult.length -gt 0)
{
try
{
$errorResult = "CODE: $($using:scenarioName) `r`nDESCRIPTION: " + $errorResult
Write-EventLog -LogName "Application" -Source "SQLSERVERAGENT" -EventID $using:eventId -EntryType Error -Message $errorResult
}
catch
{
write-host("Creating SQLSERVERAGENT Source in EventViewer")
[System.Diagnostics.EventLog]::CreateEventSource("SQLSERVERAGENT", "Application")
}
}
}
$maxRam = [double]$($using:maxRam) #deepthi
<#
write-host ("---------------------------------------------------------------")
$typeOfVar = $usedRamPerc.GetType()
write-host ("---------------->usedRamPerc = $usedRamPerc, $typeOfVar" )
$typeOfVar = $maxRam.GetType()
write-host ("---------------->maxRam = $maxRam, $typeOfVar" )
write-host ("---------------------------------------------------------------")
#>
#if ( $usedRamPerc -gt $($using:maxRam))
if ( $usedRamPerc -gt $maxRam)
{
write-host ("Exceed the threshold limit of RAM consumption");
$eventData = ("RAM exceeded threshold for : " + $env:COMPUTERNAME.ToLower() + " RAM threshold: " + $using:maxRam + " actual RAM usage: " + $usedRamPerc)
monitoringCreateEventViewerEntry($eventData)
}
return ('{"chart":"hwRam", "name":"' + $env:COMPUTERNAME.ToLower() + '", "value":"' + $usedRamPerc + '"},')
}
#NETWORK
$jsonData += Invoke-Command -ComputerName $server -ScriptBlock {
Get-CimInstance -Query "Select BytesTotalPersec from Win32_PerfFormattedData_Tcpip_NetworkInterface" | Select-Object BytesTotalPerSec |
Foreach-Object {
#write-host $_.BytesTotalPerSec;
$Size_GB = $_.BytesTotalPerSec
write-host ("Network used", $Size_GB);
function monitoringCreateEventViewerEntry($errorResult)
{
if ($errorResult.length -gt 0)
{
try
{
$errorResult = "CODE: $($using:scenarioName) `r`nDESCRIPTION: " + $errorResult
Write-EventLog -LogName "Application" -Source "SQLSERVERAGENT" -EventID $using:eventId -EntryType Error -Message $errorResult
}
catch
{
write-host("Creating SQLSERVERAGENT Source in EventViewer")
[System.Diagnostics.EventLog]::CreateEventSource("SQLSERVERAGENT", "Application")
}
}
}
$maxNetwork = [uint64]$($using:maxNetwork) #deepthi
<#
write-host ("---------------------------------------------------------------")
$typeOfVar = $Size_GB.GetType()
write-host ("---------------->Size_GB = $Size_GB, $typeOfVar" )
$typeOfVar = $maxNetwork.GetType()
write-host ("---------------->maxNetwork = $maxNetwork, $typeOfVar" )
write-host ("---------------------------------------------------------------")
#>
#if( $Size_GB -gt $($using:maxNetwork))
if( $Size_GB -gt $maxNetwork)
{
write-host ("Exceed the threshold limit of NETWORK");
$eventData = ("Network exceeded threshold for : " + $env:COMPUTERNAME.ToLower() + " Network threshold: " + $using:maxNetwork + " actual Network usage: " + $Size_GB)
monitoringCreateEventViewerEntry($eventData)
}
return ('{"chart":"hwNetwork", "name":"' + $env:COMPUTERNAME.ToLower() + '", "value":"' + $Size_GB + '"},')
}
}
#Swap
$jsonData += Invoke-Command -ComputerName $server -ScriptBlock {
$colItems = get-wmiobject -class "Win32_PageFileUsage" -namespace "root\CIMV2" -computername localhost
foreach ($swap in $colItems)
{
$usedSwap=[math]::Round(($swap.CurrentUsage / $swap.AllocatedBaseSize * 100))
write-host ("Swap used ",$usedSwap);
$maxSwap = [double]$($using:maxSwap) #deepthi
<#
write-host ("---------------------------------------------------------------")
$typeOfVar = $usedSwap.GetType()
write-host ("---------------->usedSwap = $usedSwap, $typeOfVar" )
$typeOfVar = $maxSwap.GetType()
write-host ("---------------->maxSwap = $maxSwap, $typeOfVar" )
write-host ("---------------------------------------------------------------")
#>
#if ($usedSwap -gt $($using:maxSwap))
if ($usedSwap -gt $maxSwap)
{
write-host (" Exceed the threshold limit of SWAP usage");
}
return ('{"chart":"hwSwap", "name":"' + $env:COMPUTERNAME.ToLower() + '", "value":"' + $usedSwap + '"},')
}
}
# Threads
$jsonData += Invoke-Command -ComputerName $server -ScriptBlock {
$threads = (Get-Process|Select-Object -ExpandProperty Threads).Count
write-host ("threads used",$threads);
$maxThreads = [int]$($using:maxThreads) #deepthi
<#
write-host ("---------------------------------------------------------------")
$typeOfVar = $threads.GetType()
write-host ("---------------->threads = $threads, $typeOfVar" )
$typeOfVar = $maxThreads.GetType()
write-host ("---------------->maxThreads = $maxThreads, $typeOfVar" )
write-host ("---------------------------------------------------------------")
#>
#if ($threads -gt $($using:maxThreads))
if ($threads -gt $maxThreads)
{
write-host ("Exceed the threshold limit of thread");
}
return ('{"chart":"hwThreads", "name":"' + $env:COMPUTERNAME.ToLower() + '", "value":"' + $threads + '"},')
}
# Disk
$jsonData += Invoke-Command -ComputerName $server -ScriptBlock {
Get-WmiObject -Class win32_logicaldisk | Select-Object DeviceId, Size, FreeSpace |
Foreach-Object {
if($_.Size -ne $null){
write-host ("Disk consumption",$_.DeviceId)
function monitoringCreateEventViewerEntry($errorResult)
{
if ($errorResult.length -gt 0)
{
try
{
$errorResult = "CODE: $($using:scenarioName) `r`nDESCRIPTION: " + $errorResult
Write-EventLog -LogName "Application" -Source "SQLSERVERAGENT" -EventID $using:eventId -EntryType Error -Message $errorResult
}
catch
{
write-host("Creating SQLSERVERAGENT Source in EventViewer")
[System.Diagnostics.EventLog]::CreateEventSource("SQLSERVERAGENT", "Application")
}
}
}
$usedDiskPerc= [math]::Round((($_.Size - $_.FreeSpace) / $_.Size * 100))
write-host $usedDiskPerc;
$maxDisk = [double]$($using:maxDisk) # deepthi
<#
write-host ("---------------------------------------------------------------")
$typeOfVar = $usedDiskPerc.GetType()
write-host ("---------------->usedDiskPerc = $usedDiskPerc, $typeOfVar" )
$typeOfVar = $maxDisk.GetType()
write-host ("---------------->maxDisk = $maxDisk, $typeOfVar" )
write-host ("---------------------------------------------------------------")
#>
#if (($_.FreeSpace.length -gt 0) -and ($usedDiskPerc -gt $($using:maxDisk)))
if (($_.FreeSpace.length -gt 0) -and ($usedDiskPerc -gt $maxDisk))
{
write-host ("Exceed the threshold limit of DISK consumption");
$eventData = ("Disk exceeded threshold for : " + $env:COMPUTERNAME.ToLower() + " Disk threshold: " + $using:maxDisk + " actual Disk usage: " + $usedDiskPerc)
monitoringCreateEventViewerEntry($eventData)
}
return ('{"chart":"hwDisk", "name":"' + $env:COMPUTERNAME.ToLower() + ' - ' + $_.DeviceId + '", "value":"' + $usedDiskPerc + '"},')
}
}
}
}
sendApiRequest
writeLog (“INFO: Done.”)
This is my code for hw.ps1 if we run with one script it is working fine
if I run entire scripts with Dashboards like api.ps1,probedisc.ps, service.ps1 and api.ps1 with xml file it was throwing some Exceptions like CommandNotFound Exception
facing this issues Could you please help to find solutions on this