-
-
Save skokhanovskiy/b88d9cb05ef98cf59e99fd0ffc525ffd to your computer and use it in GitHub Desktop.
Send UDP datagram from Powershell
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function Send-Datagram | |
{ | |
[CmdletBinding(SupportsShouldProcess = $true)] | |
param | |
( | |
[Parameter(Position = 0, Mandatory = $true, ValueFromPipeline = $true)] | |
[AllowEmptyCollection()] | |
[AllowEmptyString()] | |
[AllowNull()] | |
[Alias('Data')] | |
$InputObject, | |
[Parameter(Position = 1, Mandatory = $true)] | |
[ValidateNotNullOrEmpty()] | |
[String] $Address, | |
[Parameter(Position = 2, Mandatory = $true)] | |
[ValidateRange(1, 65535)] | |
[Alias('DstPort', 'DestPort', 'DestinationPort')] | |
[Int] $Port, | |
[Parameter()] | |
[ValidateRange(1, 65535)] | |
[Alias('SrcPort')] | |
[Int] $SourcePort, | |
[Parameter()] | |
[System.Text.Encoding] $Encoding = [System.Text.Encoding]::UTF8 | |
) | |
begin | |
{ | |
$IpAddress = $null | |
$ParseResult = [System.Net.IPAddress]::TryParse($Address, [Ref] $IpAddress) | |
if (-not $ParseResult) | |
{ | |
try | |
{ | |
$AddressList = [System.Net.Dns]::GetHostAddresses($Address) | |
if (-not $AddressList) | |
{ | |
throw "Unable to resolve address: $Address." | |
} | |
} | |
catch | |
{ | |
throw $_ | |
} | |
$IpAddress = $AddressList[0] | |
} | |
$Endpoint = [System.Net.IPEndPoint]::new($IpAddress, $Port) | |
if ($SourcePort) | |
{ | |
$UdpClient = [System.Net.Sockets.UdpClient]::new($SourcePort) | |
} | |
else | |
{ | |
$UdpClient = [System.Net.Sockets.UdpClient]::new() | |
} | |
} | |
process | |
{ | |
foreach ($Object in $InputObject) | |
{ | |
try | |
{ | |
if ($Object -isnot [System.String]) | |
{ | |
$Object = $Object.ToString() | |
} | |
$EncodedData = $Encoding.GetBytes($Object) | |
if ($PSCmdlet.ShouldProcess("$Object to $IpAddress`:$Port", $PSCmdlet.MyInvocation.InvocationName)) | |
{ | |
[Void] $UdpClient.Send($EncodedData, $EncodedData.Length, $Endpoint) | |
} | |
} | |
catch | |
{ | |
$_ | Write-Error | |
} | |
} | |
} | |
end | |
{ | |
$UdpClient.Close() | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment