Ярлыки Chart.point не будут работать с 2 диаграммами, созданными вместо 1 - PullRequest
0 голосов
/ 09 декабря 2018

Работа с диаграммами в PowerShill отображает результаты проверки связи Windows с различными серверами.Этот код прекрасно работает на одном графике.Он отображает столбчатую диаграмму в виде столбцов с ошибками на красной полосе с отображением количества неудачных проверок, и если время отклика больше некоторого числа, столбец отображается желтым и помечается как время отклика.

#region setup chart
$Chart = New-Object -TypeName System.Windows.Forms.DataVisualization.Charting.Chart
$Chart.Size = '600,750'
#$Chart.BackColor = [system.drawing.color]::Transparent

$ChartArea = New-Object -TypeName System.Windows.Forms.DataVisualization.Charting.ChartArea
$ChartArea.AxisX.Title = 'Response times'
$ChartArea.AxisY.Title = 'Time in MS '
$ChartArea.AxisX.Interval = '1'
$ChartArea.AxisX.LabelStyle.Enabled = $true
$ChartArea.AxisX.LabelStyle.Angle = 90
$Chart.ChartAreas.Add($ChartArea)
$Chart.Series.Add('Good')
$Chart.Series['Good']["DrawingStyle"] = "Cylinder"
$Chart.Series['Good'].ChartType = [System.Windows.Forms.DataVisualization.Charting.SeriesChartType]::StackedBar
 $Chart.Series['Good'].Color = [system.drawing.color]::Green
 $Title = New-Object -TypeName System.Windows.Forms.DataVisualization.Charting.Title
$Chart.Titles.Add($Title)
$Chart.Titles[0].Text = 'Ping Monitor (Active Pings)'

#endregion chart

function processPINGS {
  BEGIN {
         $curpoint=0
         $global:Chart.Series['Good'].points.clear()
    }#begin

Process {
ForEach($key in $global:status.keys)
{ 
         switch ($global:status[$key].FailedType){
              0 { 
                  $Value = $global:Chart.Series['Good'].Points.AddXY("$($global:status[$key].name)","$($global:status[$key].'Response Time')")
                 }   #end case 0 
              1 { $Value = $global:Chart.Series['Good'].Points.AddXY("$($global:status[$key].name)","150")
                           $global:Chart.Series['Good'].points[$curpoint].color = [system.drawing.color]::RED
                           $global:Chart.Series['Good'].points[$curpoint].label = "$($global:status[$key].'Failed Pings') Failed Pings"
                 }#end case 1
             2 {$Value=$global:Chart.Series['Good'].Points.AddXY("$($global:status[$key].name)","$($status[$key].'Response Time')")
                       $global:Chart.Series['Good'].points[$curpoint].color = [system.drawing.color]::Yellow
                       $global:Chart.Series['Good'].points[$curpoint].label = "$($global:status[$key].'Response Time') MS"
                }#end case 2
           }#end switch
       $curpoint++
    }#end foreach Key
   }#end of process block
}#end of function processPINGS

$PingCount = 0
Do {
    Ping-Machines
    processPINGS
   $Chart.SaveImage("$scriptpath\Chartgoodpings.png", "PNG")
   Start-Sleep -seconds 30
   }Until (PingCount -gt 120)

Итак, теперь я хотел сделать 2 диаграммы: одну для машин, которые проверяют, и одну для машин, которые не проверяют, чтобы кто-то мог быстро увидеть все машины, которые не проверяют.Я скопировал настройку диаграммы следующим образом

    $NoPingChart = New-Object -TypeName System.Windows.Forms.DataVisualization.Charting.Chart
    $NoPingChart.Size = '600,750'
    $NoPingChartArea = New-Object -TypeName System.Windows.Forms.DataVisualization.Charting.ChartArea
    $NoPingChartArea.AxisX.Title = 'Response times'
    $NoPingChartArea.AxisY.Title = 'Time in MS '
    $NoPingChartArea.AxisX.Interval = '1'
    $NoPingChartArea.AxisX.LabelStyle.Enabled = $true
    $NoPingChartArea.AxisX.LabelStyle.Angle = 90
    $NoPingChart.ChartAreas.Add($NoPingChartArea)
    $NoPingChart.Series.Add('Good')
    $NoPingChart.Series['Good']["DrawingStyle"] = "Cylinder"
    $NoPingChart.Series['Good'].ChartType = [System.Windows.Forms.DataVisualization.Charting.SeriesChartType]::StackedBar
    $NoPingChart.Series['Good'].Color = [system.drawing.color]::RED
    $Title = New-Object -TypeName System.Windows.Forms.DataVisualization.Charting.Title
   $NoPingChart.Titles.Add($Title)
   $NoPingChart.Titles[0].Text = 'Ping Monitor (Failed Pings)'  

Затем я изменил функцию processPings, чтобы сохранить результаты для плохих пингов на новый график следующим образом

function processPINGS {
  BEGIN {
         $curpoint=0
         $global:Chart.Series['Good'].points.clear()
    }#begin

Process {
ForEach($key in $global:status.keys)
{ 
         switch ($global:status[$key].FailedType){
              0 { 
                  $Value = $global:Chart.Series['Good'].Points.AddXY("$($global:status[$key].name)","$($global:status[$key].'Response Time')")
                 }   #end case 0 
              1 { $Value = $global:NoPingChart.Series['Good'].Points.AddXY("$($global:status[$key].name)","150")
                           $global:NoPingChart.Series['Good'].points[$curpoint].color = [system.drawing.color]::RED
                           $global:NoPingChart.Series['Good'].points[$curpoint].label = "$($global:status[$key].'Failed Pings') Failed Pings"
                 }#end case 1
             2 {$Value=$global:Chart.Series['Good'].Points.AddXY("$($global:status[$key].name)","$($status[$key].'Response Time')")
                       $global:Chart.Series['Good'].points[$curpoint].color = [system.drawing.color]::Yellow
                       $global:Chart.Series['Good'].points[$curpoint].label = "$($global:status[$key].'Response Time') MS"
                }#end case 2
           }#end switch
       $curpoint++
    }#end foreach Key
   }#end of process block
}#end of function processPINGS

Затем я снова запустил программус изменениями и как только он попытался создать точки в случае 1 или 2, я получаю следующие ошибки:

  The property 'Label' cannot be found on this object. Verify that the property exists and can be set.
   At C:\ToolBox\PINGMonitor\pingChart-v3.ps1:94 char:87
    + ... nts[$curpoint].Label = "$($global:status[$key].'Failed Pings') Failed ...
       +                               ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
      + CategoryInfo          : InvalidOperation: (:) [], RuntimeException
       + FullyQualifiedErrorId : PropertyNotFound

 The property 'Label' cannot be found on this object. Verify that the property exists and can be set.
At C:\ToolBox\PINGMonitor\pingChart-v3.ps1:94 char:87
+ ... nts[$curpoint].Label = "$($global:status[$key].'Failed Pings') Failed ...
+                               ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
   + CategoryInfo          : InvalidOperation: (:) [], RuntimeException
   + FullyQualifiedErrorId : PropertyNotFound

  The property 'Color' cannot be found on this object. Verify that the property exists and can be set.
 At C:\ToolBox\PINGMonitor\pingChart-v3.ps1:99 char:23
+ ...             
   $global:GoodChart.Series['Good'].points[$curpoint].Color  ...
 + 
  ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
   + CategoryInfo          : InvalidOperation: (:) [], RuntimeException
   + FullyQualifiedErrorId : PropertyNotFound

Остановил программу и посмотрел на свойства диаграммы

$global:NoPingChart.Series['bad'].points[$curpoint]
  XValue                      : 0
  YValues                     : {150}
  IsEmpty                     : False
  Name                        : DataPoint
  Label                       : 

Затем установите ярлык вручную

$global:NoPingChart.Series['bad'].points[$curpoint].label = "Test Label"
$global:NoPingChart.Series['bad'].points[$curpoint]
XValue                      : 0
YValues                     : {150}
IsEmpty                     : False
Name                        : DataPoint
Label                       : Test Label

Как вы можете, ярлык есть, и я могу изменить его вручную.Я бью себя по столу, пытаясь понять, что происходит.Любая помощь будет оценена

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...