powershellscripts.com

Tutorials  Tutorials

Powershell Basics
Introduction to Windows PowerShell Part 1
Introduction to Windows PowerShell Part 2
Introduction to Windows PowerShell Part 3
PowerShell Script Signing
PowerShell Scheduled Tasks
PowerShell Networking Tasks

Powershell Advanced Tutorials
PowerShell and VMware Introduction



 



PowerShell Networking Tasks

PowerShell makes it easy to automate and test network connectivity, pull IP information from workstations and servers, figure out active network sessions, and a slew of other network related tasks. The great thing about PowerShell is how easy it makes accessing WMI, .Net classes, and traditional cmd line tools. We'll take a look at a couple of different ways to perform each networking task.

Pulling network adaptor information
From the command line we would of course issue the ipconfig command

PS C:\> ipconfig

Windows IP Configuration

Ethernet adapter Local Area Connection:
   Connection-specific DNS Suffix  . :
   Link-local IPv6 Address . . . . . : fe80::cd57:a149:ffff:1111
   IPv4 Address. . . . . . . . . . . : xxx.xxx.xxx.xxx
   Subnet Mask . . . . . . . . . . . : xxx.xxx.xxx.xxx
   Default Gateway . . . . . . . . . : xxx.xxx.xxx.xxx
....
Using VBScript we might have pulled the IP info via WMI, we can do the same thing with PowerShell
PS C:\> $Items = Get-WMIObject -class "Win32_NetworkAdapterConfiguration" -computername . `
 | Where{$_.IpEnabled -Match "True"}
PS C:\> $ipinfo = "IPAddress : " + $Items.IPAddress + "`n"
PS C:\> $ipinfo = $ipinfo + "Subnet : " + $Items.IPSubnet + "`n"
PS C:\> $ipinfo = $ipinfo + "DNS Servers : " + $Items.DNSServerSearchOrder + "`n"
PS C:\> $ipinfo
IPAddress : xxx.xxx.xxx.xxx fe80::b006:2406:ffff:1111
Subnet : xxx.xxx.xxx.xxx 64
DNS Servers : xxx.xxx.xxx.xxx xxx.xxx.xxx.xxx
Another way to get the information using a one liner would be:
Get-WmiObject -Class Win32_NetworkAdapterConfiguration -Filter IPEnabled=TRUE
All properties and methods for Win32_NetworkAdapterConfiguration can be found here


Setting Network Adapter Properties
WMI let's us make changes to network adapters via PowerShell as well.
PS C:\> $Items = Get-WMIObject -class "Win32_NetworkAdapterConfiguration" -computername . | Where{$_.IpEnabled -Match "True"}
PS C:\> Foreach($Item in $Items) {
>>     $ip = xxx.xxx.xxx.xxx
>>     $subnet = xxx.xxx.xxx.xxx
>>     $gateway = xxx.xxx.xxx.xxx
>>     $dns = xxx.xxx.xxx.xxx
>>     $Item.EnableStatic($ip, $subnet)
>>     $Item.SetGateways($gateway)
>>     $Item.SetDNSServerSearchOrder($dns)
>>     $Item.SetDynamicDNSRegistration("FALSE")
}


Show network statics
Netstat is the command line tool to show session activity
PS C:\> netstat -an
Active Connections
  Proto  Local Address          Foreign Address        State
  TCP    0.0.0.0:80             0.0.0.0:0              LISTENING
  TCP    0.0.0.0:135            0.0.0.0:0              LISTENING
  TCP    0.0.0.0:443            0.0.0.0:0              LISTENING
  TCP    0.0.0.0:445            0.0.0.0:0              LISTENING
  TCP    0.0.0.0:1433           0.0.0.0:0              LISTENING
  TCP    0.0.0.0:3389           0.0.0.0:0              LISTENING
We can also directly access the .Net classes to pull this info
PS C:\> $globalIP = [System.Net.NetworkInformation.IPGlobalProperties]::GetIPGlobalProperties()
PS C:\> $globalIP | get-member

   TypeName: System.Net.NetworkInformation.SystemIPGlobalProperties

Name                    MemberType Definition
----                    ---------- ----------
Equals                  Method     bool Equals(System.Object obj)
GetActiveTcpConnections Method     System.Net.NetworkInformation.TcpConnectionInformation[] GetActiveTcpConnections()
GetActiveTcpListeners   Method     System.Net.IPEndPoint[] GetActiveTcpListeners()
GetActiveUdpListeners   Method     System.Net.IPEndPoint[] GetActiveUdpListeners()
GetHashCode             Method     int GetHashCode()
GetIcmpV4Statistics     Method     System.Net.NetworkInformation.IcmpV4Statistics GetIcmpV4Statistics()
GetIcmpV6Statistics     Method     System.Net.NetworkInformation.IcmpV6Statistics GetIcmpV6Statistics()
GetIPv4GlobalStatistics Method     System.Net.NetworkInformation.IPGlobalStatistics GetIPv4GlobalStatistics()
GetIPv6GlobalStatistics Method     System.Net.NetworkInformation.IPGlobalStatistics GetIPv6GlobalStatistics()
GetTcpIPv4Statistics    Method     System.Net.NetworkInformation.TcpStatistics GetTcpIPv4Statistics()
GetTcpIPv6Statistics    Method     System.Net.NetworkInformation.TcpStatistics GetTcpIPv6Statistics()
GetType                 Method     type GetType()
GetUdpIPv4Statistics    Method     System.Net.NetworkInformation.UdpStatistics GetUdpIPv4Statistics()
GetUdpIPv6Statistics    Method     System.Net.NetworkInformation.UdpStatistics GetUdpIPv6Statistics()
ToString                Method     string ToString()
DhcpScopeName           Property   System.String DhcpScopeName {get;}
DomainName              Property   System.String DomainName {get;}
HostName                Property   System.String HostName {get;}
IsWinsProxy             Property   System.Boolean IsWinsProxy {get;}
NodeType                Property   System.Net.NetworkInformation.NetBiosNodeType NodeType {get;}
So, seeing active connections is as easy as this
PS C:\> $globalIP.GetActiveTcpConnections()
State LocalEndPoint                           RemoteEndPoint
----- -------------                           --------------
Established xxx.xxx.xxx.xxx:3389                       xxx.xxx.xxx.xxx:51305
Established xxx.xxx.xxx.xxx:51350                      xxx.xxx.xxx.xxx:80
Established xxx.xxx.xxx.xxx:51351                      xxx.xxx.xxx.xxx:80
Established xxx.xxx.xxx.xxx:51352                      xxx.xxx.xxx.xxx:80


Test network connection
We'll skip showing how ping works, the PowerShell equivalent of course adds more features and returns values in an object
PS C:\> Test-Connection -Computername google.com -count 3

Source        Destination     IPV4Address      IPV6Address                    Bytes    Time(ms)
------        -----------     -----------      -----------                    -----    --------
localhost        google.com      74.125.227.14    {}                              32       10
localhost        google.com      74.125.227.14    {}                              32       10
localhost        google.com      74.125.227.14    {}                              32       10
Telnet is typically used to test port connectivity from the cmd line, a quick PowerShell one liner for this is
 (new-object Net.Sockets.TcpClient).Connect("google.com", 80)
If you want to have a little more flexibility, control the timeout, and clean up the output, it just takes a few more lines
$IP = "google.com"
$port = 80
$client = new-Object Net.Sockets.TcpClient
$Connection = $client.BeginConnect($IP,$port,$null,$null)
$TimeOut = $Connection.AsyncWaitHandle.WaitOne(2000,$false)
if(!$TimeOut)   {$client.Close()
   echo "Port $port is closed on $IP."
     }
else {echo "Port $port up on $IP"}
To scan a range of ports we can use the .. notation
#Port Scan a single host
442..446 | % { echo ((new-object Net.Sockets.TcpClient).Connect("localhost",$_)) "$_ is open"} 2>out-null
We scan ports 442 thru 446, foreach port, if the port is found open we display it, STDERR is redirected to "null". As a side note, PowerShell supports unix style representation of STDIN, STDOUT, and STDERR, associating each of them to their respective numerals 0, 1, and 2.