Skip to content

Instantly share code, notes, and snippets.

@samikshajuneja
Created January 16, 2023 13:25
Show Gist options
  • Save samikshajuneja/02ce1abaaf4e600be61fd8e19042f9d2 to your computer and use it in GitHub Desktop.
Save samikshajuneja/02ce1abaaf4e600be61fd8e19042f9d2 to your computer and use it in GitHub Desktop.
Powercli Scripts
$alarmlist=gc C:\Users\samiksha.juneja\Desktop\hostlist.txt
$vc="THC2EXTVC01"
Connect-VIServer -Server $vc -User administrator@vsphere.local -Password Tiagptu0813!
foreach($alarm in $alarmlist)
{
$alarmname=$alarm -split ';'
$alarmname[0]
$yellowval=$alarmname[1]
$redval=$alarmname[2]
$aobj=Get-AlarmDefinition $alarmname[0] -Server $vc -ErrorAction Stop|get-view
$ex=New-Object -TypeName VMware.Vim.MetricAlarmExpression
if($aobj.info.expression.type)
{
$ex.red=$redval
$ex.RedInterval=$aobj.info.Expression.redinterval
#"redinterval " +$aobj.info.Expression.redinterval
$ex.yellow=$yellowval
$ex.YellowInterval=$aobj.info.Expression.yellowinterval
#"yellowinterval" + $aobj.info.Expression.yellowinterval
$ex.Operator=$aobj.info.Expression.operator
$ex.type=$aobj.info.Expression.type
#$metr=new-object VMware.Vim.PerfMetricId
#$metr.CounterId=300
#$ex.metric=[int]$aobj.info.Expression.metric
$ex.metric=New-Object VMware.Vim.PerfMetricId
$ex.Metric.CounterId=$aobj.info.Expression.metric
$ex.Metric.Instance=""
}
else
{ $ex.red=$redval
$ex.RedInterval=$aobj.info.Expression.expression.redinterval
#"redinterval " +$aobj.info.Expression.redinterval
$ex.yellow=$yellowval
$ex.YellowInterval=$aobj.info.Expression.expression.yellowinterval
#"yellowinterval" + $aobj.info.Expression.yellowinterval
$ex.Operator="isAbove"
$ex.type=$aobj.info.Expression.expression.type
#$metr=new-object VMware.Vim.PerfMetricId
#$metr.CounterId=300
$ex.metric=New-Object VMware.Vim.PerfMetricId
$ex.Metric.CounterId=$aobj.info.Expression.expression.metric.counterid
$ex.Metric.Instance=""
}
"ex"
$ex.Metric.CounterId
$spec= New-Object VMware.Vim.AlarmSpec
#$spec.name= "datastore current usage" #$aobj.info.name
#$spec.SystemName=$aobj.info.SystemName
$spec.Description="datastore current usage"
$spec.Expression=$ex
# Action
<# $actionGroup = New-Object VMware.Vim.GroupAlarmAction
$actionTrigger = New-Object VMware.Vim.AlarmTriggeringAction
$emailAction = New-Object VMware.Vim.SendEmailAction
$emailAction.ToList = 'samiksha.juneja@nttdata.com'
$emailAction.Subject = 'Alarm {alarmName} fired!'
$emailAction.Body = "{eventDescription}"
$emailAction.CcList = ''
$actionTrigger.Action += $emailAction
$actionTrigger.Green2yellow = $TRUE
$actionTrigger.Yellow2red = $TRUE
$trans1 = New-Object VMware.Vim.AlarmTriggeringActionTransitionSpec
$trans1.StartState = [VMware.Vim.ManagedEntityStatus]::green
$trans1.FinalState = [VMware.Vim.ManagedEntityStatus]::yellow
$trans1.Repeats = $false
$actionTrigger.TransitionSpecs += $trans1
$trans2 = New-Object VMware.Vim.AlarmTriggeringActionTransitionSpec
$trans2.StartState = [VMware.Vim.ManagedEntityStatus]::yellow
$trans2.FinalState = [VMware.Vim.ManagedEntityStatus]::red
$trans2.Repeats = $false
$actionTrigger.TransitionSpecs += $trans2
$actionGroup.Action += $actionTrigger
$spec.Action = $actionGroup#>
$spec.Action=$aobj.info.Action
$spec.Actionfrequency=$aobj.info.ActionFrequency
$spec.setting=$aobj.info.Setting
$spec.Enabled=$true;
#$spec
#$spec.Expression
"aobj"
#$aobj.info.action.action.action
#$spec
#$spec.action.action.action
#$aobj.ReconfigureAlarm($spec)
$entity=get-datastore -Server $vc|?{$_.type -like "vsan"}|get-view
$alarmMgr = Get-View AlarmManager -Server $vc
foreach($e in $entity)
{
$e.name
$e.moref
$spec.name="Datastore usage on $($e.Name)"
$alarmMgr.createalarm($e.MoRef,$spec)
}
<#$newoutput=Get-AlarmDefinition -Name "datastore current usage" -Server $vc |get-view
$outval=$newoutput.info.expression
#Out-File -filepath "C:\users\samiksha.juneja\Desktop\$vc.txt" -InputObject "$($alarmname[0]) `t $outval " -Append
$prop=[ordered]@{VC=$vc;AlarmName=$alarmname[0];Prev_yellowval=$aobj.info.expression.yellow;Prev_RedVal=$aobj.info.expression.red; `
New_RedVal=$outval.Red;New_Yellowval=$outval.Yellow;Enabled=$newoutput.info.Enabled}
$obj=New-Object PSObject -Property $prop
$obj|export-csv -Path "C:\users\samiksha.juneja\Desktop\$vc alarm.csv" -NoTypeInformation -Append#>
$aobj=$null
#"aobj" + $aobj.Info
}
Disconnect-VIServer $vc -Confirm:$false
$alarmlist=gc C:\Users\samiksha.juneja\Desktop\hostlist.txt
$vc="thk2trvc03"
Connect-VIServer -Server $vc -User administrator@vsphere.local -Password Tiagptu0813!
foreach($alarm in $alarmlist)
{
$alarmname=$alarm -split ';'
$alarmname[0]
$yellowval=$alarmname[1]
$redval=$alarmname[2]
$aobj=Get-AlarmDefinition $alarmname[0] -Server $vc -ErrorAction Stop|get-view
"hi"
($aobj).count
$ex=New-Object -TypeName VMware.Vim.MetricAlarmExpression
if($aobj.info.expression.type)
{
$ex.red=$redval
$ex.RedInterval=$aobj.info.Expression.redinterval
#"redinterval " +$aobj.info.Expression.redinterval
$ex.yellow=$yellowval
$ex.YellowInterval=$aobj.info.Expression.yellowinterval
#"yellowinterval" + $aobj.info.Expression.yellowinterval
$ex.Operator=$aobj.info.Expression.operator
$ex.type=$aobj.info.Expression.type
#$metr=new-object VMware.Vim.PerfMetricId
#$metr.CounterId=300
#$ex.metric=[int]$aobj.info.Expression.metric
$ex.metric=New-Object VMware.Vim.PerfMetricId
$ex.Metric.CounterId=$aobj.info.Expression.metric.counterid
$ex.Metric.Instance=""
}
else
{ $ex.red=$redval
$ex.RedInterval=$aobj.info.Expression.expression.redinterval
#"redinterval " +$aobj.info.Expression.redinterval
$ex.yellow=$yellowval
$ex.YellowInterval=$aobj.info.Expression.expression.yellowinterval
#"yellowinterval" + $aobj.info.Expression.yellowinterval
$ex.Operator="isAbove"
$ex.type=$aobj.info.Expression.expression.type
#$metr=new-object VMware.Vim.PerfMetricId
#$metr.CounterId=300
$ex.metric=New-Object VMware.Vim.PerfMetricId
$ex.Metric.CounterId=$aobj.info.Expression.expression.metric.counterid
$ex.Metric.Instance=""
}
"ex"
($aobj.info.SystemName).count
$spec= New-Object VMware.Vim.AlarmSpec
$spec.name= $aobj.info.name
$spec.SystemName=$aobj.info.SystemName
$spec.Description="datastore current usage"
$spec.Expression=$ex
$spec.Action=$aobj.info.Action
$spec.Actionfrequency=$aobj.info.ActionFrequency
$spec.setting=$aobj.info.Setting
$spec.Enabled=$true;
#$spec
#$spec.Expression
"aobj"
$aobj.ReconfigureAlarm($spec)
$aobj.info.expression.red
$newoutput=Get-AlarmDefinition -Name $alarmname[0] -Server $vc |get-view
$outval=$newoutput.info.expression
"out"
$outval.red
#Out-File -filepath "C:\users\samiksha.juneja\Desktop\$vc.txt" -InputObject "$($alarmname[0]) `t $outval " -Append
$prop=[ordered]@{VC=$vc;AlarmName=$alarmname[0];Prev_yellowval=$aobj.info.expression.yellow;Prev_RedVal=$aobj.info.expression.red; `
New_RedVal=$outval.Red;New_Yellowval=$outval.Yellow;Enabled=$newoutput.info.Enabled}
$obj=New-Object PSObject -Property $prop
$obj|export-csv -Path "C:\users\samiksha.juneja\Desktop\$vc alarm.csv" -NoTypeInformation -Append
$aobj=$null
}
Disconnect-VIServer $vc -Confirm:$false
$storeName = Read-host "Enter Datastore name"
$vc="thk2trvc02"
Connect-VIServer $vc
$alarmMgr = Get-View AlarmManager -Server $vc
$entity = Get-View -ViewType Datastore -Property Name -Filter @{'Name'=$storeName} -Server $vc
# Find metric ID
$si = Get-View ServiceInstance -Server $vc
$perfMgr = Get-View -Id $si.Content.PerfManager -Server $vc
$metricId = $perfMgr.PerfCounter |
where{$_.GroupInfo.Key -eq 'disk' -and $_.NameInfo.Key -eq 'used' -and $_.RollupType -eq 'latest'} |
select -ExpandProperty Key
$metricId
# AlarmSpec
$spec = New-Object VMware.Vim.AlarmSpec
$spec.Name = "Datastore-$($entity.Name)"
$spec.Description = "$($entity.Name) disk utilization"
$spec.Enabled = $TRUE
# Expression
$expression = New-Object VMware.Vim.MetricAlarmExpression
$expression.Operator = "isAbove"
$expression.red = 8000
$expression.type = "Datastore"
$expression.yellow = 6000
$expression.metric = New-Object VMware.Vim.PerfMetricId
$expression.metric.counterid = 281
$expression.metric.instance = ""
$spec.expression = New-Object VMware.Vim.AndAlarmExpression
$spec.expression.expression += $expression
# Action
$actionGroup = New-Object VMware.Vim.GroupAlarmAction
$actionTrigger = New-Object VMware.Vim.AlarmTriggeringAction
$emailAction = New-Object VMware.Vim.SendEmailAction
$emailAction.ToList = 'samiksha.juneja@nttdata.con'
$emailAction.Subject = 'Alarm {alarmName} fired!'
$emailAction.Body = "{eventDescription}"
$emailAction.CcList = ''
$actionTrigger.Action += $emailAction
$actionTrigger.Green2yellow = $TRUE
$actionTrigger.Yellow2red = $TRUE
$trans1 = New-Object VMware.Vim.AlarmTriggeringActionTransitionSpec
$trans1.StartState = [VMware.Vim.ManagedEntityStatus]::green
$trans1.FinalState = [VMware.Vim.ManagedEntityStatus]::yellow
$trans1.Repeats = $false
$actionTrigger.TransitionSpecs += $trans1
$trans2 = New-Object VMware.Vim.AlarmTriggeringActionTransitionSpec
$trans2.StartState = [VMware.Vim.ManagedEntityStatus]::yellow
$trans2.FinalState = [VMware.Vim.ManagedEntityStatus]::red
$trans2.Repeats = $false
$actionTrigger.TransitionSpecs += $trans2
$actionGroup.Action += $actionTrigger
$spec.Action = $actionGroup
# Transaction
$trans = New-Object VMware.Vim.AlarmTriggeringActionTransitionSpec
$trans.StartState = "yellow"
$trans.FinalState = "red"
$trans.Repeats = $false
# Setting
$spec.Setting = New-Object VMware.Vim.AlarmSetting
$spec.Setting.ReportingFrequency = 0
$spec.Setting.ToleranceRange = 0
$spec.ActionFrequency = 0
# Create alarm.
$alarmMgr.CreateAlarm($entity.MoRef, $spec)
Disconnect-VIServer $vc
$path="C:\Users\samiksha.juneja\Desktop"
$vc="thk2trvc02"
$cred=gc "$path\cred_info.txt"
foreach($v in $vc)
{
try{ Connect-VIServer $v -User $cred[0] -Password $cred[1] -ErrorAction Stop }
catch{out-file -FilePath "$path\dserror.txt" -InputObject "$v `t $($_.exception.message)"}
$report=Get-Datastore -Server $v |select -first 5 name,@{n="total(gb)";e={[math]::Round($_.capacitygb)}},@{n="free(gb)";e={[math]::Round($_.freespacegb)}}, `
@{n="free(%)";e={[math]::Round(($_.freespacegb/$_.capacitygb)*100)}}, `
@{N='ProvisionedGB';E={[math]::Round(($_.ExtensionData.Summary.Capacity - $_.ExtensionData.Summary.FreeSpace + $_.ExtensionData.summary.Uncommitted)/1GB)}} `
,@{N='Provisioned(%)';E={[math]::Round(([math]::Round(($_.ExtensionData.Summary.Capacity - $_.ExtensionData.Summary.FreeSpace + `
$_.ExtensionData.summary.Uncommitted)/1GB)/$_.capacitygb)*100)}}
$htmloutput=ConvertTo-Html -PreContent "$(get-date)" -Body ($report|ConvertTo-Html -Fragment)
$htmloutput|Out-File -FilePath "$path\ds_usage.html" -Append
Disconnect-VIServer $v -Confirm:$false
}
#
###alarms
$iopath="C:\Users\samiksha.juneja\Documents\WindowsPowerShell\Reports"
$time=get-date -Format dd_MM_yyyy_hh_mm
$OutputFile="$iopath\triggered_alarm\Report_$($time)_.html"
$cred=gc "$iopath\cred_info.txt"
$htmlheader = @"
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script type="text/javascript">
`$(document).ready(function(){
`$( "td:contains('yellow')" ).css('background-color', '#ffff4d'); //If yellow alarm triggered set cell background color to yellow
`$( "td:contains('yellow')" ).text('Warning'); //Replace text 'yellow' with 'Warning'
`$( "td:contains('red')" ).css('background-color', '#ff3333' ); //If yellow alarm triggered set cell background color to red
`$( "td:contains('red')" ).text('Alert'); //Replace text 'red' with 'Alert'
});
</script>
"@
Write-Host "Connecting to vCenter" -foregroundcolor "magenta"
$vcenterlist=gc "$iopath\vc.txt"
$Reportvc=@()
foreach($vclist in $vcenterlist)
{
try{
$vc=connect-viserver $vclist -User $cred[0] -Password $cred[1] -ErrorAction Stop|get-view
$esx_all = get-view $vc.content.rootfolder
foreach ($esx in $esx_all){
foreach($triggered in $esx.TriggeredAlarmState){
If ($triggered.OverallStatus -like "red" -or $triggered.OverallStatus -like "yellow"){
$lineitem={} | Select status,vc,entity,alarm,time,entitytype,ackby,acktime
$alarmDef = Get-View -Id $triggered.Alarm
$alarmname=$alarmDef.Info.Name|Out-String
$lineitem.Alarm =$alarmname
$en=Get-View $triggered.Entity -ErrorAction stop
$lineitem.entity=$en.name|Out-String
$lineitem.vc=$vclist
$lineitem.status=$triggered.OverallStatus
$lineitem.time=$triggered.Time
$lineitem.entitytype=$triggered.Entity.Type
$lineitem.ackby=$triggered.AcknowledgedByUser
$lineitem.acktime=$triggered.AcknowledgedTime
$lineitem
$Reportvc +=$lineitem
}
}
}
Disconnect-VIServer $vclist -Confirm:$false
}
catch{Out-File -FilePath "$iopath\triggered_alarm\alarmerror$date.txt" -InputObject "$vclist`t$($_.exception.message)" -Append }
}
$report=@()
foreach($report1 in $reportvc)
{
if($Report1.alarm -notlike "*Virtual machine CPU usage*" -and $Report1.alarm -notlike "*Virtual machine memory usage*")
{
$report +=$Report1
}
}
$style = "<style>BODY{font-family: Arial; font-size: 10pt;}"
$style = $style + "TABLE{border: 1px solid black; border-collapse: collapse;}"
$style = $style + "TH{border: 1px solid black; background: #66b3ff; padding: 5px; }"
$style = $style + "TD{border: 1px solid black; padding: 5px; }"
$style = $style + "</style>"
$htmloutput=ConvertTo-Html -Title "Itsoneknot" -Head "<div id='title'>PowerCLI Alarms</div><div id='subtitle'>Report generated: $(Get-Date)</div>`n$htmlheader`n<noscript>JS not supported</noscript>`n$style" -Body "$($report | ConvertTo-Html -Fragment)"
$htmloutput=$htmloutput -replace '<td>red</td>','<td id="red" bgcolor="red" >Alert</td>'
$htmloutput=$htmloutput -replace '<td>yellow</td>','<td id="yellow" bgcolor="yellow" >Warning</td>'
$op=$htmloutput| Out-File "$OutputFile" -Append
$result=Send-MailMessage -Attachments $OutputFile -SmtpServer smtp.tenethealth.net -Body "$htmloutput" -BodyAsHtml -Port 25 -Subject "Alarms $(get-date)" `
-To "samiksha.juneja@nttdata.com" -From "vcenter@tenethealth.com" -Priority High -DeliveryNotificationOption OnSuccess
$result
$lun="naa.60050768018187cc30000000000003d9"
$esx=get-cluster "ptc hie*" |Get-VMHost
foreach($h in $esx){
$hb=get-vmhost $h.Name|Get-VMHostHba -Type FibreChannel
foreach($hba in $hb){$hbas=$hba.device;Get-ScsiLun -Hba $hba|?{$_.CanonicalName -like "*$lun"}|select @{n="host";e={$h.name}},@{n="hba";e={$hbas}},canonicalname,capacitygb}
}
$date= Get-Date -Format "MM/dd/yyyy:hh:mm tt"
$moduleexist=Get-Module VAMI*
if(!($moduleexist))
{
try
{
Get-Module VAMI* -ListAvailable|Import-Module -ErrorAction stop
}
catch
{
Out-File -FilePath $PSScriptRoot\VAMIError.log -InputObject "$date`t $($Error[0].exception.message)" -Append
}
}
$vclist='thk2trvc03'
foreach($vc in $vclist)
{
try
{
Connect-CisServer -Server $vc -User administrator@vsphere.local -Password 'Tiagptu0813!' -ErrorAction Stop
$date= Get-Date -Format "MM/dd/yyyy:hh:mm tt"
$health=Get-VAMIHealth
if($health.HealthCPU -ne 'green' -or $health.HealthMem -ne 'green' -or $health.HealthSoftware -ne 'green' -or $health.HealthOverall -ne 'green' -or $health.HealthStorage -ne 'green' -or $health.HealthSwap -ne 'green' -or $health.HealthVCDB -ne 'green')
{
Out-File -FilePath $PSScriptRoot\VAMIError.log -InputObject "$date`t $health" -Append
}
else
{
Out-File -FilePath $PSScriptRoot\VAMIInfo.log -InputObject "$date`t $health" -Append
}
}
catch
{
Out-File -FilePath $PSScriptRoot\VAMIError.log -InputObject "$date`t $($Error[0].exception.message)" -Append
}
Disconnect-CisServer * -Confirm:$false
}
measure-command{$diskvm=@()
Get-HardDisk -vm * -Server thdbkvc01 |%{
$r=""|select VM,VM_disk,filename,diskformat,disktype,capacity,datastore,datastorecapacity,datastorefree,datastoretype
$dsdetail=Get-View $_.ExtensionData.backing.datastore -Property name,summary.type,summary.capacity,summary.freespace
$r.vm=$_.Parent
$r.vm_disk=$_.name
$r.filename=$_.filename
$r.diskformat=$_.storageformat
$r.disktype=$_.DiskType
$r.capacity=$_.capacitygb
$r.datastore=$dsdetail.name
$r.datastorecapacity=[math]::round($dsdetail.summary.capacity/1tb)
$r.datastorefree=[math]::round($dsdetail.summary.freespace/1tb)
$r.datastoretype=$dsdetail.Summary.Type
$diskvm +=$r
}
$diskvm|Export-Excel -Path $iopath\tenvm.xlsx -WorksheetName vmdkdetails -Append
}
$diskvm.Count
$vmlist=gc c:\users\samiksha.juneja\desktop\hostlist.txt
#$vmlist="TENHDCTHSFSQL1"
foreach($vm in $vmlist)
{
$vminfo=Get-VM $vm |select name,powerstate
if($vminfo.powerstate -eq "PoweredOn")
{
$time=[datetime]"06/12/2019 1:00:00 AM"
$end=[datetime]"06/12/2019 6:00:00 AM"
$a=Get-Stat -Entity $vm -Stat "mem.usage.average","cpu.usage.average" -Start $time -Finish $end -ErrorAction SilentlyContinue|?{$_.metricid -like "*.usage.*"}|select Entity,metricid,value,unit,timestamp |export-csv -Path D:\Samiksha\dummy.csv -NoTypeInformation
$b=import-csv -Path D:\Samiksha\dummy.csv
$b|export-csv -Path D:\samiksha\Nikhat_report.csv -NoTypeInformation -append
}
#get-stat -Entity "TENHDCTHSFSQL1" -Stat "datastore.read.average","datastore.write.average" -Start $time -ErrorAction SilentlyContinue|?{$_.metricid -like "virtualdisk.read.average"}
}
$vmname=gc $PSScriptRoot\vmlist.txt
foreach($vm in $vmname)
{
$uptime= get-vm $vm|Get-stat -Stat sys.uptime.latest -MaxSamples 1 -Realtime|select @{n="val";e={$_.value/(60*60*24)}}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment