Functions/Send-StatsD.ps1

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
<#
.SYNOPSIS
    Sends data to a statsd UDP service endpoint
.DESCRIPTION
    PowerShell function to send UDP data to a statsd endpoint,
    like DogStatsD service in a ASCII encoded byte-format.

    The function supports the basic -Verbose and -Debug
    cmdletbindings.
.PARAMETER Data
    Mandatory - String data to be sent to the statsD service
.PARAMETER ComputerName
    Optional - ComputerName (Hostname or IPaddress) of the
    target statsd service
        Default is 127.0.0.1 for localhost
.PARAMETER Port
    Optional - Port for the target statsd service
        Default is 8125
.EXAMPLE
    Send-StatsD -Data 'sample_gauge:1985|g'
.EXAMPLE
    'sample_gauge:1985|g' | Send-StatsD
.EXAMPLE
    Send-StatsD -Data 'sample_histogram:12|h' -ComputerName '192.168.0.20'
.EXAMPLE
    Send-StatsD -Data 'sample_histogram:12|h' -ComputerName '192.168.0.20' -Port 8128
#>


function Send-StatsD {
    [CmdletBinding(SupportsShouldProcess=$true)]
    param(
        [parameter(Mandatory=$true, ValueFromPipeline=$true)]
        [ValidateNotNullOrEmpty()]
        [string]$Data,

        [Parameter()]
        [ValidateNotNullOrEmpty()]
        [string]$ComputerName='127.0.0.1',

        [Parameter()]
        [ValidateRange(1,65535)]
        [int]$Port=8125
    )

    Begin {
        Write-Verbose "Targeting $($ComputerName):$Port UDP endpoint.."
        $UdpClient = New-Object System.Net.Sockets.UdpClient($ComputerName, $Port)
    }

    Process {
        try {
            Write-Debug "Encoding data:`n$Data"
            $bytes=[System.Text.Encoding]::ASCII.GetBytes($Data)

            Write-Debug "Sending Encoded Data: `n$bytes"
            if ($PSCmdlet.ShouldProcess($ComputerName, "Sending $($bytes.Count) bytes.")) {
                $sent=$UdpClient.Send($bytes,$bytes.length)
                Write-Debug "Data Length sent: $sent"
            }
        }
        catch {
            Write-Error $_
        }
    }

    End {
        $UdpClient.Close()
        $UdpClient.Dispose()
        $UdpClient = $null
    }
}