Automation

 View Only
Expand all | Collapse all

Create a custom CPU alarm for VM using PowerCli

mk5213

mk5213Sep 09, 2020 08:10 PM

LucD

LucDSep 09, 2020 08:15 PM

  • 1.  Create a custom CPU alarm for VM using PowerCli

    Posted Feb 05, 2020 06:57 AM

    Hello! I need to create an alarm on the CPU for each virtual machine, after the alarm has worked, I need to send a message to the user's mail, mail information should be taken from the user attribute of VM (I did it myself). Please help me with this matter.



  • 2.  RE: Create a custom CPU alarm for VM using PowerCli

    Posted Feb 06, 2020 09:16 AM

    Can you provide some more details about the requirement?

    What do you mean by "... alarm on the CPU"?
    Is that when CPU utilisation goes over a specific watermark?

    Also, what do you mean by "... mail information should be taken from the user attribute"?

    Is that the email To address?



  • 3.  RE: Create a custom CPU alarm for VM using PowerCli

    Posted Feb 06, 2020 09:30 AM

    What do you mean by "... alarm on the CPU"?-  for example standart vcenter alarm "Virtual machine CPU usage"

    Is that when CPU utilisation goes over a specific watermark? - Yes, it is

    I need to create an alarm action on each virtual machine (by the name of the machine) this is the main requirement

    Also, what do you mean by "... mail information should be taken from the user attribute"?

    Is that the email To address?

    foreach($vmName in $vmNames){

    $entity = Get-VM -Name $vmName

    $mail=(Get-Annotation -Entity (get-vm $vmName) -CustomAttribute Contact).value

    $action = New-AlarmAction -Email -Subject 'Test' -To "$mail" -AlarmDefinition $def

    I need something like this:



  • 4.  RE: Create a custom CPU alarm for VM using PowerCli

    Posted Feb 06, 2020 09:44 AM

    That is in fact the solution.
    What is missing from that code?



  • 5.  RE: Create a custom CPU alarm for VM using PowerCli

    Posted Feb 06, 2020 09:49 AM

    I can't found this part for cpu

    $stat = 'disk.used.latest'

    $statSplit = $stat.Split('.')

    $si = Get-View ServiceInstance

    $perfMgr = Get-View -Id $si.Content.PerfManager

    $metric = $perfMgr.PerfCounter | where{$_.GroupInfo.Key -eq $statSplit[0] -and $_.NameInfo.Key -eq $statSplit[1] -and $_.RollupType -eq $statSplit[2]}

    $alarmMgr = Get-View AlarmManager

    $entity = Get-View -ViewType VirtualMachine -Filter @{'Name'=$vmName}

    $spec = New-Object VMware.Vim.AlarmSpec

    $spec.Name = $alarmName

    $spec.Enabled = $true

    $spec.Description = $alarmDescription

    $metricId = New-Object VMware.Vim.PerfMetricId

    $metricId.CounterId = $metric.Key

    $metricId.Instance = ''

    $expression = New-Object VMware.Vim.MetricAlarmExpression

    $expression.Metric += $metricId

    $expression.Type = 'VirtualMachine'

    $expression.Operator = [VMware.Vim.MetricAlarmOperator]::isAbove

    $expression.Yellow = $yellowGB * 1MB

    $expression.Red = $redGB * 1MB

    $spec.Expression = $expression



  • 6.  RE: Create a custom CPU alarm for VM using PowerCli

    Posted Feb 06, 2020 10:14 AM

    In the recent PowerCLI release there are new cmdlets to create metric based alarms.

    Something like this

    $vm = Get-VM -Name MyVM

    $userEmail = (Get-Annotation -Entity $vm -CustomAttribute 'Contact').value

    $sAlarmTrigger = @{

        Metric = Get-Metric -MetricGroup 'CPU' -Name 'usage' | select -First 1

        MetricAlarmOperator = 'Above'

        Yellow = 50

        Red = 75

        EntityType = 'VirtualMachine'

    }

    $trigger = New-AlarmTrigger @sAlarmTrigger


    $sAlarmAction = @{

        Email = $true

        Subject = 'CPU Usage high'

        To = $userEmail

    }

    $action = New-AlarmAction @sAlarmAction


    $sAlarmDef = @{

        Name = 'CPU High'

        Description = 'Trigger alarm when CPU utilisation is too high'

        Entity = $vm

        AlarmTrigger = $trigger

        AlarmAction = $action

    }

    New-AlarmDefinition @sAlarmDef



  • 7.  RE: Create a custom CPU alarm for VM using PowerCli

    Posted Feb 06, 2020 10:41 AM

    Thank you, but I had error if I use 2 or more vms.

    Get-Annotation: Cannot convert "System.Object []" to type "VMware.VimAutomation.ViCore.Types.V1.Inventory.Inven
    toryItem "required for the Entity parameter. The specified method is not supported.
    line: 1 character: 38
    + $ userEmail = (Get-Annotation -Entity $ vm -CustomAttribute 'Contact').



  • 8.  RE: Create a custom CPU alarm for VM using PowerCli

    Posted Feb 06, 2020 10:50 AM

    You seem to have a blank between $ and vm on the Entity parameter



  • 9.  RE: Create a custom CPU alarm for VM using PowerCli

    Posted Feb 06, 2020 10:55 AM

    I haven't blunk between $ and vm

    $vm = Get-VM -Name "test1","test2"

    $userEmail = (Get-Annotation -Entity $vm -CustomAttribute 'Contact').value

    Get-Annotation : Не удается преобразовать "System.Object[]" в тип "VMware.VimAutomation.ViCore.Types.V1.Inventory.InventoryItem", необходимый для п

    араметра "Entity". Указанный метод не поддерживается.

    строка:1 знак:38

    + $userEmail = (Get-Annotation -Entity $vm -CustomAttribute 'Contact').



  • 10.  RE: Create a custom CPU alarm for VM using PowerCli
    Best Answer

    Posted Feb 06, 2020 11:25 AM

    It looked like that from the previous screenshot.

    But if you want to do this for multiple VMs, the script need some changes.

    Something like this

    Get-VM -Name 'Test1', 'Test2' -PipelineVariable vm |

    ForEach-Object -Process {

        $userEmail = (Get-Annotation -Entity $vm -CustomAttribute 'Contact').value

        $sAlarmTrigger = @{

            Metric              = Get-Metric -MetricGroup 'CPU' -Name 'usage' | Select-Object -First 1

            MetricAlarmOperator = 'Above'

            Yellow              = 50

            Red                 = 75

            EntityType          = 'VirtualMachine'

        }

        $trigger = New-AlarmTrigger @sAlarmTrigger


        $sAlarmAction = @{

            Email   = $true

            Subject = 'CPU Usage high'

            To      = $userEmail

        }

        $action = New-AlarmAction @sAlarmAction


        $sAlarmDef = @{

            Name         = 'CPU High'

            Description  = 'Trigger alarm when CPU utilisation is too high'

            Entity       = $vm

            AlarmTrigger = $trigger

            AlarmAction  = $action

        }


        New-AlarmDefinition @sAlarmDef

    }



  • 11.  RE: Create a custom CPU alarm for VM using PowerCli

    Posted Feb 06, 2020 12:41 PM

    Excellent! It works.

    How can I use the miltipale mail address?

    New-AlarmAction: Unable to bind the "To" parameter to the target. Exception when setting "To": "Invalid email address: 1@test.com; 2@test.om "



  • 12.  RE: Create a custom CPU alarm for VM using PowerCli

    Posted Feb 06, 2020 01:50 PM

    Multiple mail addresses should be separated with a comma afaik.

    Try replacing the ; with a ,



  • 13.  RE: Create a custom CPU alarm for VM using PowerCli

    Posted Feb 06, 2020 01:55 PM

    The comma did n't help

    New-AlarmAction :Cannot bind “To” parameter to target. An exception "To" : "Invalid email address: 1@test.com,2@test.com"



  • 14.  RE: Create a custom CPU alarm for VM using PowerCli

    Posted Feb 06, 2020 02:45 PM

    Seems to work for me with an array of strings

    To      = 'user1@local.lab','user2@local.lab'

    In your case you could try

    To      = $userEmail.Split(';')


  • 15.  RE: Create a custom CPU alarm for VM using PowerCli

    Posted Feb 06, 2020 02:54 PM

    It's work! Thank you so much!

    Get-VM -Name 'Test1','Test2' -PipelineVariable vm |

    ForEach-Object -Process {

        $userEmail = (Get-Annotation -Entity $vm -CustomAttribute 'Contact').value

        $sAlarmTrigger = @{

            Metric              = Get-Metric -MetricGroup 'CPU' -Name 'usage' | Select-Object -First 1

            MetricAlarmOperator = 'Above'

            Yellow              = 50

            Red                 = 75

            EntityType          = 'VirtualMachine'

        }

        $trigger = New-AlarmTrigger @sAlarmTrigger

        $sAlarmAction = @{

            Email   = $true

            Subject = 'CPU Usage high'

            To      = $userEmail.Split(';')

        }

        $action = New-AlarmAction @sAlarmAction

        $sAlarmDef = @{

            Name         = "CPU High_$vm"

            Description  = 'Trigger alarm when CPU utilisation is too high'

            Entity       = $vm

            AlarmTrigger = $trigger

            AlarmAction  = $action

        }

        New-AlarmDefinition @sAlarmDef

    }



  • 16.  RE: Create a custom CPU alarm for VM using PowerCli

    Posted Feb 07, 2020 08:48 AM

    LucD​ Hello, how  I can create $sAlarmTrigger like this?

    or set time option for this

      $sAlarmTrigger = @{

            Metric              = Get-Metric -MetricGroup 'CPU' -Name 'usage' | Select-Object -First 1

            MetricAlarmOperator = 'Above'

            Yellow              = 50

            Red                 = 75

            EntityType          = 'VirtualMachine'

        }

        $trigger = New-AlarmTrigger @sAlarmTrigger

    and I had incorrect alarms

    Target: Test1

    Previous Status: Gray

    New Status: Red

    Alarm Definition:

    ([Yellow metric Is above 0%; Red metric Is above 0%] OR [Yellow metric Is above 0%; Red metric Is above 0%])

    Current values for metric/state:

    Metric CPU Usage = 30% OR Metric CPU Usage = 30%

    Description:

    Alarm 'CPU High_test1' on MSK-DPRO-APL555 changed from Gray to Red



  • 17.  RE: Create a custom CPU alarm for VM using PowerCli

    Posted Feb 07, 2020 11:35 AM

    There were a few issues with my previous solution.

    The Get-Metric cmdlet doesn't really one to select the correct metric.

    The values for the thresholds need to be multiplied by 100.

    And the duration can be defined.

    My new version which should fix the issues.

    $vmNames = 'test01','test02'

    $metricName = 'cpu.usage.average'


    $mGroup,$mName,$mRollup = $metricName.Split('.')

    $si = Get-View ServiceInstance

    $perfMgr = Get-View -Id $si.Content.PerfManager

    $metric = $perfMgr.PerfCounter |

        where{$_.GroupInfo.Key -eq $mGroup -and

              $_.NameInfo.Key -eq $mName -and

              $_.RollupType -eq $mRollup}


    Get-VM -Name $vmNames-PipelineVariable vm |

    ForEach-Object -Process {

        $userEmail = (Get-Annotation -Entity $vm -CustomAttribute 'Contact').value

        $sAlarmTrigger = @{

            Metric              = Get-Metric -MetricGroup 'CPU' -Name 'usage' | where{$_.Key -eq $metric.Key}

            MetricAlarmOperator = 'Above'

            Red                 = 7500

            RedIntervalSeconds  = 300

            EntityType          = 'VirtualMachine'

        }

        $trigger = New-AlarmTrigger @sAlarmTrigger


        $sAlarmAction = @{

            Email   = $true

            Subject = 'CPU Usage high'

            To      = $userEmail.Split(';')

        }

        $action = New-AlarmAction @sAlarmAction


        $sAlarmDef = @{

            Name         = 'CPU High'

            Description  = 'Trigger alarm when CPU utilisation is too high'

            Entity       = $vm

            AlarmTrigger = $trigger

            AlarmAction  = $action

        }


        New-AlarmDefinition @sAlarmDef

    }



  • 18.  RE: Create a custom CPU alarm for VM using PowerCli

    Posted Feb 07, 2020 12:25 PM

    Thank you!



  • 19.  RE: Create a custom CPU alarm for VM using PowerCli

    Posted Feb 26, 2020 01:25 PM

    Hi LucD, I need your help again .... I can't set up a mail resend(after 5 minutes) notification for this alarm. can you help me?

    I can only do this after creating an alarm and can't change the source of the alarm, and therefore additional steps must be taken.

    Get-AlarmDefinition -Name "CPU High DBA340"| Get-AlarmAction | New-AlarmActionTrigger -StartStatus Red -EndStatus Yellow -Repeat

    Get-AlarmDefinition -Name "CPU High DBA340"| Get-AlarmAction|Get-AlarmActionTrigger |select -First 1 | Remove-AlarmActionTrigger -Confirm:$false

    Get-AlarmDefinition -Name "CPU High DBA340"| Get-AlarmAction | set-AlarmActionTrigger -StartStatus Yellow -EndStatus Red -Repeat

    Get-AlarmDefinition -Name "CPU High DBA340"| Get-AlarmAction|Get-AlarmActionTrigger |select -First 1 | Remove-AlarmActionTrigger -Confirm:$false



  • 20.  RE: Create a custom CPU alarm for VM using PowerCli

    Posted Feb 26, 2020 01:52 PM

    You mean something like this?

    $alarm = Get-AlarmDefinition -Name 'CPU High'

    $action = Get-AlarmAction -AlarmDefinition $alarm -ActionType SendEmail

    Remove-AlarmAction -AlarmAction $action -Confirm:$false

    $trigger = New-AlarmActionTrigger -StartStatus $action.Trigger[0].StartStatus -EndStatus $action.Trigger[0].EndStatus -Repeat

    New-AlarmAction -AlarmDefinition $alarm -Email -Subject $action.Subject -To $action.To -AlarmActionTrigger $trigger


    Set-AlarmDefinition -AlarmDefinition $alarm -ActionRepeatMinutes 5 -Confirm:$false



  • 21.  RE: Create a custom CPU alarm for VM using PowerCli

    Posted Feb 26, 2020 02:02 PM

    No, I want to make changes to the current script.

    $ErrorActionPreference= 'Stop'

    $metricName = 'cpu.usage.average'

    $mGroup,$mName,$mRollup = $metricName.Split('.')

    $si = Get-View ServiceInstance

    $perfMgr = Get-View -Id $si.Content.PerfManager

    $metric = $perfMgr.PerfCounter |

        where{$_.GroupInfo.Key -eq $mGroup -and

              $_.NameInfo.Key -eq $mName -and

              $_.RollupType -eq $mRollup}

    $VMcluster=read-host "Enter Cluster name"

    $VM_with_contact=(Get-Cluster $VMcluster|get-vm |Get-Annotation -CustomAttribute 'Contact'|where{$_.Value -ne ""}).AnnotatedEntity.name

    Get-VM $VM_with_contact|?{$_.Name -notlike  "*Template*" -and $_.Name -notlike  "*Old*"} -PipelineVariable vm |

    ForEach-Object -Process {

        $userEmail = (Get-Annotation -Entity $vm -CustomAttribute 'Contact').value -replace " "

        $sAlarmTrigger = @{

            Metric              = Get-Metric -MetricGroup 'CPU' -Name 'usage' | where{$_.Key -eq $metric.Key}

            MetricAlarmOperator = 'Above'

            Red                 = 9500

            RedIntervalSeconds  = 86400

            EntityType          = 'VirtualMachine'

        }

        $trigger = New-AlarmTrigger @sAlarmTrigger

        $sAlarmAction = @{

            Email   = $true

    Body = "$vm CPU Usage is above 95% for 24 hours , please check your OS."

            Subject = "High CPU Usage $vm"

            To      = @($userEmail.Split(';'))

        }

        $action = New-AlarmAction @sAlarmAction

        $sAlarmDef = @{

            Name         = "CPU High $vm"

            Description  = 'Trigger alarm when CPU utilisation is too high'

            Entity       = $vm

            AlarmTrigger = $trigger

            AlarmAction  = $action

        }

        New-AlarmDefinition @sAlarmDef|ft -AutoSize

    }

    $ErrorActionPreference= 'Continue'

    And after running the script, I want to see the following:

    Get-AlarmDefinition -Name "CPU High DBA340"| Get-AlarmAction |Get-AlarmActionTrigger

    StartStatus     EndStatus       Repeat

    -----------     ---------       ------

    Yellow          Red             TRUE



  • 22.  RE: Create a custom CPU alarm for VM using PowerCli

    Posted Feb 26, 2020 02:48 PM

    Ok, try like this

    $vmNames = 'test01','test02'

    $metricName = 'cpu.usage.average'


    $mGroup,$mName,$mRollup = $metricName.Split('.')

    $si = Get-View ServiceInstance

    $perfMgr = Get-View -Id $si.Content.PerfManager

    $metric = $perfMgr.PerfCounter |

        where{$_.GroupInfo.Key -eq $mGroup -and

              $_.NameInfo.Key -eq $mName -and

              $_.RollupType -eq $mRollup}


    Get-VM -Name $vmNames -PipelineVariable vm |

    ForEach-Object -Process {

        Get-AlarmDefinition -Name 'CPU High' -Entity $_ -ErrorAction SilentlyContinue |

        Remove-AlarmDefinition -Confirm:$false

        $userEmail = (Get-Annotation -Entity $vm -CustomAttribute 'Contact').value


        $sAlarmTrigger = @{

            Metric              = Get-Metric -MetricGroup 'CPU' -Name 'usage' | where{$_.Key -eq $metric.Key}

            MetricAlarmOperator = 'Above'

            Red                 = 7500

            RedIntervalSeconds  = 300

            EntityType          = 'VirtualMachine'

        }

        $trigger = New-AlarmTrigger @sAlarmTrigger


        $sActionTrigger = @{

            StartStatus = 'yellow'

            EndStatus = 'red'

            Repeat = $true

        }

        $actionTrigger = New-AlarmActionTrigger @sActionTrigger


        $sAlarmAction = @{

            Email   = $true

            Subject = 'CPU Usage high'

            To      = $userEmail

            AlarmActionTrigger = $actionTrigger

        }

        $action = New-AlarmAction @sAlarmAction


        $sAlarmDef = @{

            Name         = 'CPU High'

            Description  = 'Trigger alarm when CPU utilisation is too high'

            Entity       = $vm

            AlarmTrigger = $trigger

            AlarmAction  = $action

            ActionRepeatMinutes = 5

        }


        New-AlarmDefinition @sAlarmDef

    }



  • 23.  RE: Create a custom CPU alarm for VM using PowerCli

    Posted Feb 28, 2020 11:56 AM

    LucD​, Thank you so much!



  • 24.  RE: Create a custom CPU alarm for VM using PowerCli

    Posted Sep 09, 2020 07:20 PM

    Hi, I am a bit confused on the creation of alarms in vcenters. I have seen CreateAlarm used but only a long time ago, is that deprecated and New-AlarmDefinition the new way of creating alarms in PowerCLI? Sorry if I am a bit misinformed on the topic. Any input is greatly appreciated, Thanks!



  • 25.  RE: Create a custom CPU alarm for VM using PowerCli

    Posted Sep 09, 2020 07:24 PM

    You are corrected, there are a number of new cmdlets for Alarms.

    See

    Get-Command -Name *Alarm*

    Some features of Alarms can not be created by these cmdlets, for those you will still need the API.



  • 26.  RE: Create a custom CPU alarm for VM using PowerCli

    Posted Sep 09, 2020 08:10 PM

    Thank you LucD, that clears it up. Right now I am just creating alarms at the datacenter level, but is there a way to create alarms for the entire vcenter? I read this here but I am a bit confused if I can make alarms for the entire vcenter?



  • 27.  RE: Create a custom CPU alarm for VM using PowerCli

    Posted Sep 09, 2020 08:10 PM



  • 28.  RE: Create a custom CPU alarm for VM using PowerCli

    Posted Sep 09, 2020 08:15 PM

    Use the Folder named Datacenters



  • 29.  RE: Create a custom CPU alarm for VM using PowerCli

    Posted Sep 10, 2020 04:28 PM

    Thank you that worked, is it possible to use for example a json or csv to initialize alarms in PowerCLI?



  • 30.  RE: Create a custom CPU alarm for VM using PowerCli

    Posted Sep 10, 2020 04:33 PM

    No, not directly.

    You can store the variable data (AlarmName, Description...) in an external file.

    But you would still need a script to define the Alarms (using the data from the external file).



  • 31.  RE: Create a custom CPU alarm for VM using PowerCli

    Posted Sep 14, 2020 07:17 PM

    Hey LucD, I am trying to get the input for alarms working with json files. I have a json file that gets taken in and successfully have everything stored in a hashtable of hashtables, but I cant get the cmdlet to work with it for some reason:

    $actionTrigger = New-AlarmActionTrigger $json.sActionTrigger

    This is the error message for this line, as well as the contents of $json.sActionTrigger:



  • 32.  RE: Create a custom CPU alarm for VM using PowerCli

    Posted Sep 14, 2020 07:43 PM

    Did you already try casting your value from the JSON file to ManagedEntityStatus type

    [VMware.Vim.ManagedEntityStatus]$json.sActionTrigger.Value


  • 33.  RE: Create a custom CPU alarm for VM using PowerCli

    Posted Sep 14, 2020 07:51 PM

    Just tried the following:

    $actionTrigger = New-AlarmActionTrigger [VMware.Vim.ManagedEntityStatus]$json.sActionTrigger.Value

    and got the following output:



  • 34.  RE: Create a custom CPU alarm for VM using PowerCli

    Posted Sep 14, 2020 08:05 PM

    What exactly do you have in $json.sActionTrigger.Value?

    Or else share part of the JSON file.



  • 35.  RE: Create a custom CPU alarm for VM using PowerCli

    Posted Sep 14, 2020 08:15 PM

    Now that you say that just checked what is stored in $json.sActionTrigger.Value and nothing comes up. But if I do run $json.sActionTrigger it shows the correct name value pairs like in my above picture, I am confused why this is.



  • 36.  RE: Create a custom CPU alarm for VM using PowerCli

    Posted Sep 14, 2020 08:16 PM

    The only thing I have stored in the JSON is the hashtable sActionTrigger:



  • 37.  RE: Create a custom CPU alarm for VM using PowerCli

    Posted Sep 14, 2020 08:34 PM

    How did you create that JSON file?
    That field should contain green,yellow or red



  • 38.  RE: Create a custom CPU alarm for VM using PowerCli

    Posted Sep 14, 2020 08:39 PM

    Yeah so I actually got this to work without nested objects in the json file. So before I just had the json only contain the startstatus, endstatus and repeat and it worked perfectly. But I am trying to contain all the hastables in one json file, so i am testing right now with just doing one hastable in the hashtable but I am hoping to add them for all the other hastables in the script. I just don't understand why the cmdlet works with a hastable, but I cant get it to work with a hashtable within a hastable. It may not be possible but I was just trying to see if you would possibly know what is wrong



  • 39.  RE: Create a custom CPU alarm for VM using PowerCli

    Posted Sep 15, 2020 05:29 AM

    I would need to see the relevant part of your code and a sample JSON extract to further analyse.



  • 40.  RE: Create a custom CPU alarm for VM using PowerCli

    Posted Sep 15, 2020 10:31 PM

    Ok if need be I can do that but I think I have an idea of what the issue is. I basically have a hash table variable I am trying to splat with. I didn't assign it  in the script like you created your splatting variable in your example, I have a function create a hashtable from a json file. I read somewhere that you cannot splat with a created hashtable, do you think this is the issue? It is treating my hashtable as the first parameter instead of using the name-value pairs in the hashtable



  • 41.  RE: Create a custom CPU alarm for VM using PowerCli

    Posted Sep 15, 2020 10:40 PM

    From my understanding this means that it is impossible to use a hashtable object to splat currently. Basically you need a created splatting variable?



  • 42.  RE: Create a custom CPU alarm for VM using PowerCli

    Posted Sep 15, 2020 11:03 PM

    Here are the important parts of the script, the commented lines work but the uncommented cmdlets next to them do not work and am trying to get them working.

    #Converts json file to hashtable variable

    function ConvertTo-Hashtable {

        [CmdletBinding()]

        [OutputType('hashtable')]

        param (

            [Parameter(ValueFromPipeline)]

            $InputObject

        )

        process {

            if ($null -eq $InputObject) {

                return $null

            }

            if ($InputObject -is [System.Collections.IEnumerable] -and $InputObject -isnot [string]) {

                $collection = @(

                    foreach ($object in $InputObject) {

                        ConvertTo-Hashtable -InputObject $object

                    }

                )

                Write-Output -NoEnumerate $collection

            } elseif ($InputObject -is [psobject]) {

                $hash = @{}

                foreach ($property in $InputObject.PSObject.Properties) {

                    $hash[$property.Name] = ConvertTo-Hashtable -InputObject $property.Value

                }

                $hash

            } else {

                $InputObject

            }

        }

    }

    $json = Get-Content -Raw -Path $jsonFile | ConvertFrom-Json | ConvertTo-Hashtable

    $mGroup,$mName,$mRollup = $json.metricName.Split('.')

    $si = Get-View ServiceInstance

    $perfMgr = Get-View -Id $si.Content.PerfManager

    $metric = $perfMgr.PerfCounter |

        where{$_.GroupInfo.Key -eq $mGroup -and

              $_.NameInfo.Key -eq $mName -and

              $_.RollupType -eq $mRollup}

    $metricParam = Get-Metric -MetricGroup $mGroup -Name $mName | where{$_.Key -eq $metric.Key}

    #$trigger = New-AlarmTrigger -metric $metricParam -MetricAlarmOperator $json.sAlarmTrigger.MetricAlarmOperator -Red $json.sAlarmTrigger.Red -RedIntervalSeconds $json.sAlarmTrigger.RedIntervalSeconds -EntityType $json.sAlarmTrigger.Entitytype

    $trigger = New-AlarmTrigger $json.sAlarmTrigger

    #$actionTrigger = New-AlarmActionTrigger -StartStatus $json.sActionTrigger.StartStatus -EndStatus $json.sActionTrigger.EndStatus -Repeat:$json.sActionTrigger.Repeat

    $actionTrigger = New-AlarmActionTrigger $json.sActionTrigger

    #$action = New-AlarmAction -Email:$json.sAlarmAction.Email -Subject $json.sAlarmAction.Subject -To $json.sAlarmAction.To -AlarmActionTrigger $actionTrigger

    $action = New-AlarmAction $json.sAlarmAction

    New-AlarmDefinition -Name $json.Name -Description $json.Description -Entity $object -AlarmTrigger $trigger -AlarmAction $action -ActionRepeatMinutes $json.ActionRepeatMinutes

    _____________________________-

    Here is the JSON

    {

        "Name": "JSON TEST ALARM",

        "Description": "CPU alarm created from json file",

        "ActionRepeatMinutes": 5,

        "metricName": "CPU.usage.average",

        "sAlarmTrigger": [{

            "MetricAlarmOperator": "Above",

            "Red": 7500,

            "RedIntervalSeconds": 300,

            "EntityType": "VirtualMachine"

        }],

        "sActionTrigger": [{

            "StartStatus": "yellow",

            "EndStatus": "red",

            "Repeat": true

        }],

        "sAlarmAction": [{

            "Email": true,

            "Subject": "CPU Usage high",

            "To": "x@gmail.com"

        }]

    }



  • 43.  RE: Create a custom CPU alarm for VM using PowerCli

    Posted Sep 16, 2020 05:21 AM

    Your ConvertTo-HashTable function does not seem to be recursive.

    Starting from your JSON file, the following does seem to work for me.

    $json = Get-Content -Raw -Path $jsonFile | ConvertFrom-Json

    $sTrigger = $json.sActionTrigger | ConvertTo-Hashtable

    New-AlarmActionTrigger @sTrigger



  • 44.  RE: Create a custom CPU alarm for VM using PowerCli

    Posted Sep 16, 2020 04:19 PM

    Thanks LucD! Things seem to be working now. Your help is greatly appreciated