Share via


Poswershell line chart

Question

Thursday, August 29, 2019 5:19 PM

Hi All,

I'd like to create a line chart with Powershell + Windows charting. The process would be this: I query the system date as "yy.mmmm.dd" and the system time as "hh:mm", separatedly (you'll see why). Furthermore, I query the stage of one specific port and the number of connections on this port. I export all this four datas into a .csv file with -append for later examination. Then, I open this .csv file and import only the 5 latest "time" and "connection number". I'd like to create the chart so, that the Title holds the actual chart title, plus the date, plus the stage of the port (because I haven't found any athor place where I could show them, like header, footer, remark, anything). Now, the Y-axis shows the query of connection numbers and the X-axis shows the timepoints when the queries have been made (say, in 5 minutes intervals). Below is my code so far. my problem is, that I'm getting an empty chart, showing only the title field. What am I doing wrong?

Thanks in advance.

Add-Type -AssemblyName System.Windows.Forms.DataVisualization

Try{
    $Date = Get-Date -f "yyyy.MMMM.dd."
    $Time = Get-Date -f "HH:mm"
        
    $connection = New-Object Net.Sockets.TcpClient
    $connection.Connect("ipaddress","portnumber")
    if($connection.Connected)
    {
        "Port is connected"
    }
    else
    {
        "Port is disconnected"
    }

    $connection_num = Get-NetTCPConnection | Where-Object { $_.LocalAddress -eq "ipaddress" -and $_.LocalPort -eq "portnumber"} | Select-Object LocalAddress, LocalPort | Measure-Object | % {$_.Count}
        
    $report = New-Object psobject
    $report | Add-Member -MemberType NoteProperty -Name Date -Value $Date
    $report | Add-Member -MemberType NoteProperty -Name Time -Value $Time
    $report | Add-Member -MemberType NoteProperty -Name Connection -Value $connection.Connected
    $report | Add-Member -MemberType NoteProperty -Name Connection_num -Value $connection_num
    
    $report | Export-Csv -Append -Path Path\linechart.csv -NoTypeInformation
}

Catch{
    Throw $_}

Try{
    if($connection.Connected)
    {
        
        $msg = "Port connected"
    }
    else
    {
        $msg = "Port disconnected"
    }

    $chart1 = [System.Windows.Forms.DataVisualization.Charting.Chart]::New()
    $chart1.Size = '1700,900'
    $chart1.Titles.Add([System.Windows.Forms.DataVisualization.Charting.Title]::New())
    $chart1.Titles[0].Font = "Arial, 24pt"
    $chart1.Titles[0].Text = "Monitoring  " + "  " + $Date + "   " + "   " + $msg
    $chart1.ChartAreas.Add([System.Windows.Forms.DataVisualization.Charting.ChartArea]::New("Default"))
    $chartarea.Name = "ChartArea1"
    $chartarea.AxisX.Interval = 10
    $chartarea.AxisY.Interval = 5
        
    $datasource = @{
        "Conn" = ((Import-Csv Path\report.csv) | Select Time, connection_num) | Select -Last 5
    }
    
    [void]$chart1.Series.Add("Data")
    $chart1.Series["Data"].ChartType = "Line"
    
    foreach ($datapoint in $datasource) {
    $x = [int]$datapoint.Connection_num
    $y = [string]$datapoint.Time
    $chart1.Series["Data"].Points.addxy($x,$y)
    }

    $imageFile = "Path\linechart.png"
    $chart1.SaveImage($imageFile,"PNG")
}
Catch{
    Throw $_}

All replies (3)

Thursday, August 29, 2019 6:16 PM ✅Answered

Here is an example the demonstrates how to display data on a chart:

Add-Type -AssemblyName System.Windows.Forms.DataVisualization

$form = New-Object Windows.Forms.Form
$form.Text = 'PowerShell Chart'
$form.Size = '600,600'
$form.Add_Shown({
    $form.Activate()
})


$form_Load = {
    Try{
        $chart = [System.Windows.Forms.DataVisualization.Charting.Chart]::New()
        $this.controls.add($chart)
        $chart.Name = 'Chart1'
        $chart.Anchor = 'Right,Top,Left'
        
        # build the chart container and add initial area
        $chart.Size = '500,400'
        $chart.Location = '40,30'
        $chart.Titles.Add([System.Windows.Forms.DataVisualization.Charting.Title]::New())
        $chart.Titles[0].Font = 'ArialBold, 18pt'
        $chart.Titles[0].Text = 'Monitoring'
        $area = [System.Windows.Forms.DataVisualization.Charting.ChartArea]::New('Default')
        $chart.ChartAreas.Add($area)
        $area.AxisX.Title = 'Measurements'
        $area.AxisY.Title = 'Measure'
        $chart.BackColor = [System.Drawing.Color]::Transparent
        
        # obtain data
        $data = @{
            CPU                            = 5
            Memory                         = 10
            Connections                    = 15
        }
        $series = $chart.Series.Add('Data')
        $series.Points.DataBindXY($data.Keys, $data.Values)
        $series['DrawingStyle'] = 'Cylinder'
    }
    Catch{
        Throw $_
    }
}

# display the chart on a form 
$form.add_Load($form_Load)

# add a save button 
$saveButton = New-Object Windows.Forms.Button
$form.controls.add($saveButton)
$saveButton.Text = 'Save'
$saveButton.Location = '500,450'
$saveButton.Anchor = 'Bottom,Right'

$saveButton.add_click({
    $saveFile = '.\Chart.png'
    $this.FindForm().Controls['Chart1'].SaveImage($saveFile, 'PNG')
    Start-Process $saveFile
})

$form.ShowDialog()

\(ツ)_/


Friday, September 6, 2019 11:39 AM

Hi,

Was your issue resolved?

If you resolved it using our solution, please "mark it as answer" to help other community members find the helpful reply quickly.

If you resolve it using your own solution, please share your experience and solution here. It will be very beneficial for other community members who have similar questions.

If no, please reply and tell us the current situation in order to provide further help.

Best Regards,

Lee

Just do it.


Tuesday, September 10, 2019 5:18 PM

Hi,

Sorry for the late answer, but I was very busy.
I accepted your adwise, though it wasn't the complete solution, but gave me ideas. :)

Here is the final working code:

Add-Type -AssemblyName System.Windows.Forms.DataVisualization

Try{
    $Date = Get-Date -f "yyyy.MMMM.dd."
    $Time = Get-Date -f "HH:mm"
        
    $connection = New-Object Net.Sockets.TcpClient
    $connection.Connect("IPADDRESS","PORTNUMBER")
    if($connection.Connected)
    {
        "Port connected"
    }
    else
    {
        "Port disconnected"
    }

    $connection_num = Get-NetTCPConnection | Where-Object { $_.LocalAddress -eq "IPADDRESS" -and $_.LocalPort -eq "PORTNUMBER"} | Select-Object LocalAddress, LocalPort | Measure-Object | % {$_.Count}
        
    $report_1 = New-Object psobject
    $report_1 | Add-Member -MemberType NoteProperty -Name Date -Value $Date
    $report_1 | Add-Member -MemberType NoteProperty -Name Time -Value $Time
    $report_1 | Add-Member -MemberType NoteProperty -Name Connection -Value $connection.Connected
    $report_1 | Add-Member -MemberType NoteProperty -Name Connection_num -Value $connection_num
    
    $report_1 | Export-Csv -Append -Path D:\Monitoring\report.csv -NoTypeInformation
}

Catch{
    Throw $_}

Try{
    if($connection.Connected)
    {
        $msg = "Port is connected"
    }
    else
    {
        $msg = "Port is disconnected"
    }
    # chart container + initial area
    $chart1 = [System.Windows.Forms.DataVisualization.Charting.Chart]::New()
    $chart1.Size = '1700,900'
    $chart1.Titles.Add([System.Windows.Forms.DataVisualization.Charting.Title]::New())
    $chart1.Titles[0].Font = "ArialBold, 24pt"
    $chart1.Titles[0].Text = "Monitoring  " + "  " + $Date + " " + $msg
    $chart1.ChartAreas.Add([System.Windows.Forms.DataVisualization.Charting.ChartArea]::New("Default"))
    $chart1.ChartAreas[0].AxisX.Minimum = 0
    $chart1.ChartAreas[0].AxisX.Maximum = 200 # if the connections are higher, it "breaks the roof", but nothing bad happens, and the chart won't ever resize itself!
    $chart1.ChartAreas[0].AxisY.Minimum = 0
    $chart1.ChartAreas[0].AxisY.Maximum = 5 # for the 5 measurement points, and here the chart won't resize itself either.
    $chart1.ChartAreas[0].AxisY.Interval = 1
    $chart1.ChartAreas[0].AxisX.Interval = 5
    
 
    # chart drawing with imported data
    $data = @{
        "Connt" = ((Import-Csv D:\Monitoring\report.csv) | Select Time, connection_num) | Select -Last 5 # I always want to see the last 5, and the .csv contains everything, I can check the datas, if needed.
    }
    
    [void]$chart1.Series.Add("Data")
    $chart1.Series["Data"].ChartType = "Line"
    $chart1.Series["Data"].BorderWidth = 4;
    
    foreach ($datapoint in $data.Connt) {
    $x = [int]$datapoint.Connection_num
    $y = [string]$datapoint.Time
    $chart1.Series["Data"].Points.addxy($y,$x)
    }  # "DataBindXY" threw exception, so I had to specify the types (int, string)
    

    # saving chart as .png file
    $imageFile = "D:\Monitoring\result.png"
    $chart1.SaveImage($imageFile,"PNG")
}
Catch{
    Throw $_}