Monday, 22 December 2008

Get-ParsedString.ps1

  1. <# 
  2. .SYNOPSIS 
  3.     Formats a number using .NET - an MSDN Sample recoded in PowerShell 
  4. .DESCRIPTION 
  5.     This script createa a number and formats it in Hex. Then a negative number 
  6.     is created and formatted several ways. Uses int32.parse method to do the  
  7.     parsing. 
  8. .NOTES 
  9.     File Name  : Get-ParsedString 
  10.     Author     : Thomas Lee - tfl@psp.co.uk 
  11.     Requires   : PowerShell V2 CTP3 
  12. .LINK 
  13.     Posted to: 
  14.     http://pshscripts.blogspot.com/2008/12/get-parsedstringps1.html 
  15.     Script also posted to MSDN at: 
  16.     http://msdn.microsoft.com/en-us/library/system.globalization.numberstyles(VS.85).aspx 
  17. .EXAMPLE 
  18.     PS c:\foo> .\Get-ParsedString.ps1 
  19.     A in hex = 10 in decimal 
  20.     '    -42    ' parsed to an int32 is '-42'. 
  21.     '    (42)   ' parsed to an int32 is '-42'. 
  22. #> 
  23.  
  24.  
  25. ### 
  26. #  Start of Script 
  27. ### 
  28.  
  29. # Parse the string as a hex value and display the value as a decimal. 
  30. $num = "A" 
  31. $val = [system.int32]::Parse($num, [System.Globalization.NumberStyles]::HexNumber) 
  32.  
  33. "{0} in hex = {1} in decimal" -f $num,$val 
  34.  
  35. # Parse the string, allowing a leading sign, and ignoring leading and trailing white spaces. 
  36. $num = "    -42    " 
  37.  
  38. # create parsing value using value__ 
  39. $format  = [System.Globalization.NumberStyles]::AllowLeadingSign.value__+ 
  40.            [System.Globalization.NumberStyles]::AllowLeadingWhite.value__ + 
  41.            [System.Globalization.NumberStyles]::AllowTrailingWhite.value__   
  42. $parsing = [System.Globalization.NumberStyles] $format      
  43.  
  44. # parse and display 
  45. $val = [system.int32]::Parse($num,$parsing) 
  46. "'{0}' parsed to an int32 is '{1}'." -f $num, $val 
  47.  
  48. # Now try a negative number 
  49. $num = "    (42)   " 
  50. $format  = [System.Globalization.NumberStyles]::AllowParentheses.value__  + 
  51.            [System.Globalization.NumberStyles]::AllowLeadingSign.value__  + 
  52.            [System.Globalization.NumberStyles]::AllowLeadingWhite.value__ + 
  53.            [System.Globalization.NumberStyles]::AllowTrailingWhite.value__ 
  54. $parsing = [System.Globalization.NumberStyles] $format              
  55.  
  56. # And parse/display it 
  57. $val = [system.int32]::Parse($num, $parsing) 
  58. "'{0}' parsed to an int32 is '{1}'." -f $num, $val 

Sunday, 21 December 2008

Get-RegexTest.ps1

  1. # Get-RegexTest.ps1 
  2. # Sample Using PowerShell 
  3. # Thomas Lee - tfl@psp.co.uk 
  4.  
  5. # Define a regular expression for currency values. 
  6. $rx = New-Object system.text.RegularExpressions.Regex "^-?\d+(\.\d{2})?$" 
  7.  
  8. # Define tests 
  9. $tests = "-42", "19.99", "0.001", "100 USD", ".34", "0.34", "1,052.21", "Jerry Garcia" 
  10.  
  11. # Now test and report 
  12. foreach ($test in $tests)  { 
  13. if ($rx.IsMatch($test)) { 
  14. "{0} is a currency value." -f $test 
  15. } 
  16. else { 
  17. "{0} is not a currency value." -f $test 
  18. } 
  19. }     

This script produces the following output:

PS C:\foo> .\GetRegexTest.ps1'
-42 is a currency value.
19.99 is a currency value.
0.001 is not a currency value.
100 USD is not a currency value.
.34 is not a currency value.
0.34 is a currency value.
1,052.21 is not a currency value.
Jerry Garcia is not a currency value.

Saturday, 20 December 2008

Get-FirewallDetails.ps1

  1. # Get-FirewallDetails.ps1 
  2. # Gets details of Windows Firewall (on Vista and Server 2008 or later) 
  3. # Runs on the local machine 
  4. # Thomas Lee - tfl@psp.co.uk 
  5.  
  6. # First create COM object for policy profile and get host name 
  7. $profile = (new-object -com HNetCfg.FwMgr).LocalPolicy.CurrentProfile 
  8. $Hostname=hostname 
  9.  
  10. # Is firewall enabled? 
  11. if ($profile.FirewallEnabled) { 
  12. "Firewall is enabled on system {0}" -f $Hostname 
  13. } 
  14. else { 
  15. "Firewall is NOT enabled on system {0}" -f $Hostname 
  16. } 
  17.  
  18. # Exceptions allowed? 
  19. if ($profile.ExceptionsNotAllowed) {"Exceptions NOT allowed"}  
  20. else {"Exceptions are allowed"} 
  21.  
  22. # Notifications? 
  23. if ($profile.NotificationsDisabled) {"Notifications are disabled"} 
  24. else {"Notifications are not disabled"} 
  25.  
  26. # Display determine global open ports  
  27. $ports = $profile.GloballyOpenPorts  
  28. if (!$ports -or $ports.count -eq 0) { 
  29. "There are no global open ports" 
  30. } 
  31. else { 
  32. "There are {0} open ports as follows:" -f $ports.count 
  33. $ports 
  34. } 
  35. "" 
  36.  
  37. # Display ICMP settings 
  38. "ICMP Settings:" 
  39. $profile.IcmpSettings 
  40.  
  41. # Display authorised applications 
  42. $apps = $profile.AuthorizedApplications  
  43. # 
  44. if (!$apps) { 
  45. "There are no authorised applications" 
  46. } 
  47. else { 
  48. "There are {0} global applications as follows:" -f $apps.count 
  49. $apps  
  50. } 
  51.  
  52. # Display authorised services 
  53. $services = $profile.services 
  54. # 
  55. if (!$services) { 
  56. "There are no authorised services" 
  57. } 
  58. else { 
  59. "There are {0} authorised services as follows:" -f $services.count 
  60. $services 
  61. } 

This script produces the following output:

PS C:\foo> .\Get-FirewallDetails.ps1
Firewall is enabled on system Cookham8
Exceptions are allowed
Notifications are disabled
There are no global open ports

ICMP Settings:
AllowOutboundDestinationUnreachable : False
AllowRedirect                       : False
AllowInboundEchoRequest             : True
AllowOutboundTimeExceeded           : False
AllowOutboundParameterProblem       : False
AllowOutboundSourceQuench           : False
AllowInboundRouterRequest           : False
AllowInboundTimestampRequest        : False
AllowInboundMaskRequest             : False
AllowOutboundPacketTooBig           : True

There are 4 global applications as follows:
Name                 : BitTorrent
ProcessImageFileName : C:\Program Files (x86)\BitTorrent\bittorrent.exe
IpVersion            : 2
Scope                : 0
RemoteAddresses      : *
Enabled              : True

Name                 : DNA
ProcessImageFileName : C:\Program Files (x86)\DNA\btdna.exe
IpVersion            : 2
Scope                : 0
RemoteAddresses      : *
Enabled              : True

Name                 : Microsoft Office OneNote
ProcessImageFileName : C:\Program Files (x86)\Microsoft Office\Office12\ONENOTE.EXE
IpVersion            : 2
Scope                : 0
RemoteAddresses      : *
Enabled              : True

Name                 : Microsoft Office Groove
ProcessImageFileName : C:\Program Files (x86)\Microsoft Office\Office12\GROOVE.EXE
IpVersion            : 2
Scope                : 0
RemoteAddresses      : *
Enabled              : True

There are 3 authorised services as follows:
Name              : File and Printer Sharing
Type              : 0
Customized        : False
IpVersion         : 2
Scope             : 0
RemoteAddresses   : *
Enabled           : True
GloballyOpenPorts : System.__ComObject

Name              : Network Discovery
Type              : 1
Customized        : True
IpVersion         : 2
Scope             : 1
RemoteAddresses   : LocalSubnet
Enabled           : True
GloballyOpenPorts : System.__ComObject

Name              : Remote Desktop
Type              : 2
Customized        : False
IpVersion         : 2
Scope             : 0
RemoteAddresses   : *
Enabled           : False
GloballyOpenPorts : System.__ComObject

Friday, 19 December 2008

Get-DomainModeEnumValues.ps1

 

  1. # Get-DomainModeEnumValues.ps1 
  2. # Prints out the values of the DomainMode Enum 
  3. # Thomas Lee - tfl@psp.co.uk 
  4.  
  5. # Enumerate System.DirectoryServices.ActiveDirectory.DomainMode 
  6.  
  7. $enums=[enum]::GetValues([System.DirectoryServices.ActiveDirectory.DomainMode]) 
  8.  
  9. # Display values 
  10. "System.Net.DirectoryServices.ActiveDirectory.DomainMode enum has {0} possible values:" -f $enums.count 
  11. $i=1 
  12. $enums | %{"Value {0}: {1}" -f $i,$_.tostring();$i++} 
  13. ""  
  14.  
  15. # Checking against an enum value  
  16. $ToCheck = "Windows2008Domain" 
  17. if ($ToCheck -eq  [System.DirectoryServices.ActiveDirectory.DomainMode]::Windows2008Domain) { 
  18. "`$ToCheck is Windows2008Domain" 
  19.     } 
  20. else { 
  21.     "`$ToCheck is NOT Windows2008Domain" 
  22.     } 

This script produces the following output:

PS C:\Foo> .\Get-DomainModeEnumValues.ps1
System.Net.DirectoryServices.ActiveDirectory.DomainMode enum has 5 possible values:
Value 1: Windows2000MixedDomain
Value 2: Windows2000NativeDomain
Value 3: Windows2003InterimDomain
Value 4: Windows2003Domain
Value 5: Windows2008Domain

$ToCheck is Windows2008Domain

Thursday, 18 December 2008

Get-ForestModeEnumValues.ps1

 

  1. # Get-ForestModeEnumValues.ps1 
  2. # Prints out the values of the ForestMode Enum 
  3. # Thomas Lee - tfl@psp.co.uk 
  4.  
  5. # Enumerate System.DirectoryServices.ActiveDirectory.forestmode 
  6.  
  7. $enums=[enum]::GetValues([System.DirectoryServices.ActiveDirectory.ForestMode]) 
  8.  
  9. # Display values 
  10. "System.Net.DirectoryServices.ActiveDirectory.Forest mode enum has {0} possible values:" -f $enums.count 
  11. $i=1 
  12. $enums | %{"Value {0}: {1}" -f $i,$_.tostring();$i++} 
  13. ""  
  14.  
  15. # Checking against an enum value  
  16. $ToCheck = "Windows2008Forest" 
  17. if ($ToCheck -eq  [System.DirectoryServices.ActiveDirectory.ForestMode]::Windows2008Forest) { 
  18. "`$ToCheck is Windows2008Forest" 
  19.     } 
  20. else { 
  21.     "`$ToCheck is NOT Windows2008Forest" 
  22.     } 

This script produces the following output:

PS C:\foo> .\Get-ForestModeEnumValues.ps1
System.Net.DirectoryServices.ActiveDirectory.Forest mode enum has 4 possible values:
Value 1: Windows2000Forest
Value 2: Windows2003InterimForest
Value 3: Windows2003Forest
Value 4: Windows2008Forest

$ToCheck is Windows2008Forest

Wednesday, 17 December 2008

Get-FSMOHolders.ps1

  1. # Get-FSMOHolders.ps1 
  2. # Gets the names of the systems holding the 5 FSMO holders 
  3. # Runs on a domain-joined machine 
  4. # Thomas Lee - tfl@psp.co.uk 
  5.  
  6. # Get host,forest and domain details 
  7. $Hostname   = hostname 
  8. $forest = [DirectoryServices.ActiveDirectory.Forest]::GetCurrentForest() 
  9. $domain = [DirectoryServices.ActiveDirectory.Domain]::GetCurrentDomain() 
  10.  
  11. #Display FSMOs, forest wide first 
  12. "For Host {0}" -f $hostname 
  13. "In Forest {0}, forest masters are: " -f $for.name 
  14. "Schema master          : {0}" -f $forest.SchemaRoleOwner.Name 
  15. "Domain Master          : {0}" -f $forest.NamingRoleOwner.Name 
  16. "" 
  17. # Current domain 
  18. "In domain {0}, domain masters are:" -f $dom.Name 
  19. "PDC Master            : {0}" -f $domain.PdcRoleOwner 
  20. "Infrastructure Master : {0}" -f $domain.InfrastructureRoleOwner 
  21. "RID Master            : {0}" -f $domain.RidRoleOwner 

This code produces the following output:

PS C:\foo> .\Get-FSMOHolders.ps1
For Host Cookham8
In Forest cookham.net, forest masters are:
Schema master          : Cookham1.cookham.net
Domain Master          : Cookham1.cookham.net

In domain cookham.net, domain masters are:
PDC Master            : Cookham1.cookham.net
Infrastructure Master : Cookham1.cookham.net
RID Master            : Cookham1.cookham.net

Tuesday, 16 December 2008

Get-System.EnvorinmentStaticProperties1.ps1

# Get-System.EnvorinmentStaticProperties1.ps1
#
This script demonstrates the static properties on System.Environment
#
Thomas Lee - tfl@psp.co.uk
#

# Get and display statics in system.environment class
"Static properties in [System.Environment]"
[System.Environment]
| Get-Member -Static -MemberType properties

# Now display the values of the simple static properties
"";"Static Property values for [System.Environment]"
"CommandLine: : {0}" -f [System.Environment]::CommandLine
"CurrentDirectory : {0}" -f [System.Environment]::CurrentDirectory
"ExitCode : {0}" -f [System.Environment]::ExitCOde
"HasShutdownStarted : {0}" -f [System.Environment]::HasShutdownStarted
"MchineName : {0}" -f [System.Environment]::MachineNam
"NewLine : {0}" -f [System.Environment]::NewLine
"OSVersion : {0}" -f [System.Environment]::OSVersion
"ProcessorCount : {0}" -f [System.Environment]::ProcessorCount
"SystemDirctory : {0}" -f [System.Environment]::SystemDirectory
"TickCount : {0}" -f [System.Environment]::TickCount
"UserDomainName : {0}" -f [System.Environment]::UserDomainName
"UserInteractive : {0}" -f [System.Environment]::UserInteractive
"UserName : {0}" -f [System.Environment]::UserName
"Version : {0}" -f [System.Environment]::Version
"WorkingSet : {0}" -f [System.Environment]::WorkingSet

# Here is the stack trace:
"";"StackTrace:"
[System.Environment]
::StackTrace
This script produces the following output:


PS C:\foo> Get-System.EnvironmentStaticProperties.ps1'
Static properties in [System.Environment]


TypeName: System.Environment

Name MemberType Definition
---- ---------- ----------
CommandLine Property static System.String CommandLine {get;}
CurrentDirectory Property static System.String CurrentDirectory {get;set;}
ExitCode Property static System.Int32 ExitCode {get;set;}
HasShutdownStarted Property static System.Boolean HasShutdownStarted {get;}
MachineName Property static System.String MachineName {get;}
NewLine Property static System.String NewLine {get;}
OSVersion Property static System.OperatingSystem OSVersion {get;}
ProcessorCount Property static System.Int32 ProcessorCount {get;}
StackTrace Property static System.String StackTrace {get;}
SystemDirectory Property static System.String SystemDirectory {get;}
TickCount Property static System.Int32 TickCount {get;}
UserDomainName Property static System.String UserDomainName {get;}
UserInteractive Property static System.Boolean UserInteractive {get;}
UserName Property static System.String UserName {get;}
Version Property static System.Version Version {get;}
WorkingSet Property static System.Int64 WorkingSet {get;}

Static Property values for [System.Environment]
CommandLine: : "C:\psp\PowerShellPlus.exe"
CurrentDirectory : C:\psp
ExitCode : 0
HasShutdownStarted : False
MchineName : COOKHAM8
NewLine :


OSVersion : Microsoft Windows NT 6.0.6001 Service Pack 1
ProcessorCount : 8
SystemDirctory : C:\Windows\system32
TickCount : -1879673533
UserDomainName : COOKHAM
UserInteractive : True
UserName : tfl
Version : 2.0.50727.1434
WorkingSet : 47669248

StackTrace:
at System.Environment.GetStackTrace(Exception e, Boolean needFileInfo)
at System.Environment.get_StackTrace()
at getter(Object )
at System.Management.Automation.DotNetAdapter.PropertyGet(PSProperty property)
at System.Management.Automation.Adapter.BasePropertyGet(PSProperty property)
at System.Management.Automation.PSProperty.GetAdaptedValue()
at System.Management.Automation.PSProperty.get_Value()
at System.Management.Automation.PropertyReferenceNode.GetValue(PSObject obj, Object property)
at System.Management.Automation.PropertyReferenceNode.Execute(Array input, Pipe outputPipe)
at System.Management.Automation.ParseTreeNode.Execute(Array input, Pipe outputPipe, ArrayList& resultList)
at System.Management.Automation.StatementListNode.ExecuteStatement(ParseTreeNode statement, Array input, Pipe outputPipe, ArrayList& resultL
at System.Management.Automation.StatementListNode.Execute(Array input, Pipe outputPipe, ArrayList& resultList)
at System.Management.Automation.ParseTreeNode.Execute(Array input, Pipe outputPipe)
at System.Management.Automation.ScriptCommandProcessor.ExecuteWithCatch(ParseTreeNode ptn, Array inputToProcess)
at System.Management.Automation.ScriptCommandProcessor.RunClause(ParseTreeNode clause, Object dollarUnderbar, Object inputToProcess)
at System.Management.Automation.ScriptCommandProcessor.Complete()
at System.Management.Automation.CommandProcessorBase.DoComplete()
at System.Management.Automation.Internal.PipelineProcessor.SynchronousExecuteEnumerate(Object input, Hashtable errorResults, Boolean enumera
at System.Management.Automation.PipelineNode.Execute(Array input, Pipe outputPipe, ArrayList& resultList)
at System.Management.Automation.StatementListNode.ExecuteStatement(ParseTreeNode statement, Array input, Pipe outputPipe, ArrayList& resultL
at System.Management.Automation.StatementListNode.Execute(Array input, Pipe outputPipe, ArrayList& resultList)
at System.Management.Automation.ParseTreeNode.Execute(Array input, Pipe outputPipe)
at System.Management.Automation.ScriptCommandProcessor.ExecuteWithCatch(ParseTreeNode ptn, Array inputToProcess)
at System.Management.Automation.ScriptCommandProcessor.RunClause(ParseTreeNode clause, Object dollarUnderbar, Object inputToProcess)
at System.Management.Automation.ScriptCommandProcessor.Complete()
at System.Management.Automation.CommandProcessorBase.DoComplete()
at System.Management.Automation.Internal.PipelineProcessor.SynchronousExecuteEnumerate(Object input, Hashtable errorResults, Boolean enumera
at System.Management.Automation.Runspaces.LocalPipeline.InvokeHelper()
at System.Management.Automation.Runspaces.LocalPipeline.InvokeThreadProc()
at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
at System.Threading.ExecutionContext.runTryCode(Object userData)
at System.Runtime.CompilerServices.RuntimeHelpers.ExecuteCodeWithGuaranteedCleanup(TryCode code, CleanupCode backoutCode, Object userData)
at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Threading.ThreadHelper.ThreadStart()


Sunday, 7 December 2008

Write-RSSStream.ps1

# Write-RSSStream.ps1
#
This sample shows how to use the XMLTextWriter
#
Based on Halr's content, but extended.
#
Thomas Lee - tfl@psp.co.uk

# Define output
$path = "c:\foo\file.xml"

# Create encoding, and create xml writer

$encoding = [System.Text.Encoding]::UTF8
$writer = New-Object System.Xml.XmlTextWriter( $Path, $encoding )
$writer.Formatting = [system.xml.formatting]::indented

# Write start of document
$writer.WriteStartDocument()

# Write Start of rss stream
$writer.WriteStartElement( "rss" )
$writer.WriteAttributeString( "version", "2.0" )

# write channel start info
$writer.WriteStartElement("channel")
$writer.WriteStartElement("title")
$writer.writestring("My Channel")
$writer.WriteEndElement() #end title
$Writer.WriteStartElement("Last Build Date")
$writer.WriteString((Get-Date).ToString())
$writer.WriteEndElement() #end last build date
$writer.WriteStartElement("subtitle")
$writer.WriteString("This Blog's subtitle")
$writer.WriteEndElement() #end subtitle

# Now here put an item in
$writer.WriteStartElement("item")
$writer.WriteStartElement("title")
$writer.WriteString("A cool RSS Feed Item")
$writer.WriteEndElement() #end title
$writer.WriteStartElement("link")
$writer.WriteString("http://pshscripts.blogspot.com")
$writer.WriteEndElement() #end link
$writer.WriteStartElement("description")
$writer.WriteString("This is the body of a blog post. It could go on, and on. ")
$writer.Writestring("Or not as the case may be!")
$writer.WriteEndElement() #end description
$writer.WriteStartElement("author")
$writer.WriteString("Thomas Lee - tfl@psp.co.uk")
$writer.WriteEndElement() #end author
$writer.WriteEndElement() #end item

# Write end of document information
$writer.WriteEndElement() # End Channel
$writer.WriteEndElement() #End RSS

# Make sure we close the file
$writer.close()

# Let's see what it has done
cat $path

This script produces the following output:

PS C:\foo> . 'C:\foo\write-rssstream.PS1'
<?xml version="1.0" encoding="utf-8"?>
<rss version="2.0">
<channel>
<title>My Channel</title>
<Last Build Date>12/5/2008 8:50:26 AM</Last Build Date>
<subtitle>This Blog's subtitle</subtitle>
<item>
<title>A cool RSS Feed Item</title>
<link>http://pshscripts.blogspot.com</link>
<description>This is the body of a blog post. It could go on, and on.
Or not
as the case may be!</description>
<author>Thomas Lee - tfl@psp.co.uk</author>
</item>
</channel>
</rss>

Saturday, 6 December 2008

PowerShell Script Library Available for Download

Thus far, I have published around 65 scripts to this blog. To help readers, I’m publishing a zip of the entire library to my www.reskit.net site. You can get the full library at http://www.reskit.net/powershell/scriptlib.zip.

I’ll try to keep this archive relatively up to date as I add new scripts. I’ll also publish the script I’ve developed that creates the zip file and uploads it to the web site!

 

Friday, 5 December 2008

Send-UDPDatagram.ps1

  1. <#  
  2. .SYNOPSIS 
  3.     Sends a UDP datagram to a port 
  4. .DESCRIPTION 
  5.     This script used system.net.socckets to send a UDP 
  6.     datagram to a particular port. Being UDP, there's 
  7.     no way to determine if the UDP datagram actually 
  8.     was received.  
  9.     for this sample, a port was chosen (20000). 
  10. .NOTES 
  11.     File Name  : Send-UDPDatagram 
  12.     Author     : Thomas Lee - tfl@psp.co.uk 
  13.     Requires   : PowerShell V2 CTP3 
  14. .LINK 
  15.     http://www.pshscripts.blogspot.com 
  16. .EXAMPLE 
  17. #> 
  18.  
  19. ### 
  20. #  Start of Script 
  21. ## 
  22.  
  23. # Define port and target IP address 
  24. # Random here! 
  25. [int] $Port = 20000 
  26. $IP = "10.10.1.100" 
  27. $Address = [system.net.IPAddress]::Parse($IP) 
  28.  
  29. # Create IP Endpoint 
  30. $End = New-Object System.Net.IPEndPoint $address, $port 
  31.  
  32. # Create Socket 
  33. $Saddrf   = [System.Net.Sockets.AddressFamily]::InterNetwork 
  34. $Stype    = [System.Net.Sockets.SocketType]::Dgram 
  35. $Ptype    = [System.Net.Sockets.ProtocolType]::UDP 
  36. $Sock     = New-Object System.Net.Sockets.Socket $saddrf, $stype, $ptype 
  37. $Sock.TTL = 26 
  38.  
  39. # Connect to socket 
  40. $sock.Connect($end) 
  41.  
  42. # Create encoded buffer 
  43. $Enc     = [System.Text.Encoding]::ASCII 
  44. $Message = "Jerry Garcia Rocks`n"*10 
  45. $Buffer  = $Enc.GetBytes($Message) 
  46.  
  47. # Send the buffer 
  48. $Sent   = $Sock.Send($Buffer) 
  49. "{0} characters sent to: {1} " -f $Sent,$IP 
  50. "Message is:" 
  51. $Message 
  52. # End of Script 

 

If you run this script and are using WireShark to capture the network traffic, you might see something like this:

image

From this trace, you can see the UDP Datagram that was sent. And since the port does not exist on the target machine (10.10.1.100), that machine returns a Destination Port Unreachable as expected.