Quantcast
Channel: PowerShell for Windows Admins » Network
Viewing all 16 articles
Browse latest View live

Changing IP Connection Metric

$
0
0

A question on the forums asked how the connection metrics could be set on a Windows system.

We need to start by identifying the network adapters using this function

function test-ipmetric {
Get-WmiObject -Class Win32_NetworkAdapter -Filter "AdapterType = ‘Ethernet 802.3′" |
foreach {
Get-WmiObject -Class Win32_NetworkAdapterConfiguration -Filter "Index=$($_.DeviceId)" |
select Description, Index, IPEnabled, IPConnectionMetric
}
}

test-ipmetric | ft -a

Description                                                                                  Index IPEnabled IPConnect
                                                                                                                               ionMetric
———–                                                                                      —–     ———    ———
NVIDIA nForce 10/100/1000 Mbps Networking Controller              7         True        20
Atheros AR5007 802.11b/g WiFi Adapter                                      11        True        10
Microsoft Virtual WiFi Miniport Adapter                                          17        False

 

I get three adapters returned

The important ones are those that have IPEnabled set to True.

identify which is to have priority then run

function set-ipmetric {
param (
[int]$index,
[int]$metric
)
Get-WmiObject -Class Win32_NetworkAdapterConfiguration -Filter "Index=$index" |
Invoke-WmiMethod -Name SetIPConnectionMetric -ArgumentList $metric
}

I used

set-ipmetric -index 7 -metric 200

set-ipmetric -index 11 -metric 100

This sets my wired to a higher metric than the wireless. If I wanted it the other way round

set-ipmetric -index 7 -metric 100

set-ipmetric -index 11 -metric 200

The system must be rebooted for the changes to take effect


Setting a Network address in Windows Server 8

$
0
0

 

Windows Server 8 & Windows 8 bring a host of new functionality to us. I wanted to try out some of it so created a new VM and installed the OS – went for full GUI for now

Opened PowerShell and ran

Set-ExecutionPolicy remotesigned
Enable-PSRemoting -Force

The NetTCPIP module has some commands for working with network addresses

Get-NetIPInterface -ConnectionState Connected

ifIndex ifAlias            AddressFamily  NlMtu(Bytes)  InterfaceMetric Dhcp    Store
——- ——-            ————-  ————  ————— —-     —–
21      Virtual Wireless   IPv6           1500          5               Disabled Active
12      Virtual LAN        IPv6           1500          5               Disabled Active
21      Virtual Wireless   IPv4           1500          5               Disabled Active
12      Virtual LAN        IPv4           1500          5               Disabled Active

The display is abridged to fit

The important points are the ifIndex and ifAlias.  The index scheme is totally   different to the Win32_NetworkAdapter*  scheme

To set the address

New-NetIPAddress -InterfaceAlias "Virtual Wireless" -IPv4Address 192.168.2.10 -PrefixLength 24 -DefaultGateway 192.168.2.1

Set-DnsClientServerAddress -InterfaceAlias "Virtual Wireless" -ServerAddresses 192.168.2.1
Set-DnsClient -InterfaceIndex 21 -ConnectionSpecificSuffix beta8.test

Notice that you have to use New-NetIPAddress. The logic seems to be that you are adding a new address to the adapter so use New*.

Set-NetIPAddress works to modify an existing address BUT you can’t change the default gateway that way!

The Set-DnsClient* cmdlets are in the DnsClient module

All of these cmdlets are based on calls to WMI classes

At the end of all that I wanted to bounce the machine any way so used

Restart-Computer

PowerShell in Practice offer today only

$
0
0

Manning have PowerShell in Practice on a half price offer today. Go to www.manning.com and use code dotd0330cc when ordering

TCP/IP Alternative Configuration: pt I The configuration

$
0
0

A question on the forum got me wondering about setting the Alternative Configuration on a TCP/IP properties of a network adapter. NICs are normally configured to either DHCP or a static address. If you use DHCP another tab “Alternative Configuration” appears on the IPv4 properties dialog. This can be set to APIPA (an address in the range 169.254.x.x/16 – ie DHCP failed) or a static address. DHCP will be tried first and if it fails the Alternative Configuration kicks in.

I had never seen anything on configuring this so started to dig.

It turns out that the information is held in the registry – big surprise! The data is a little difficult to track down

## http://technet.microsoft.com/en-us/library/bb457118.aspx            
$index = 7            
$HKLM = 2147483650 #HKEY_LOCAL_MACHINE            
$data = @{}            
            
$nic = Get-WmiObject -Class Win32_NetworkAdapterConfiguration -Filter "Index=$index"            
            
$key = "SYSTEM\CurrentControlSet\services\Tcpip\Parameters\Interfaces\$($nic.SettingID)"            
            
$rc = Invoke-WmiMethod -Class StdRegProv -Name EnumValues -ArgumentList $hklm, $key            
            
if ($rc.ReturnValue -eq 0) {            
              
  $num = $rc.Types.count -1            
              
  for ($i=0; $i -le $num; $i++){            
                 
     switch ($rc.Types[$i]) {            
       1 {$value = Invoke-WmiMethod -Class StdRegProv -Name GetStringValue -ArgumentList $hklm, $key, $($rc.sNames[$i]) | select -ExpandProperty sValue}            
       2 {$value = Invoke-WmiMethod -Class StdRegProv -Name GetExpandedStringValue -ArgumentList $hklm, $key, $($rc.sNames[$i]) | select -ExpandProperty sValue}            
       3 {$value = Invoke-WmiMethod -Class StdRegProv -Name GetBinaryValue -ArgumentList $hklm, $key, $($rc.sNames[$i]) | select -ExpandProperty uValue}            
       4 {$value = Invoke-WmiMethod -Class StdRegProv -Name GetDWORDValue -ArgumentList $hklm, $key, $($rc.sNames[$i]) | select -ExpandProperty uValue}            
       7 {$value = Invoke-WmiMethod -Class StdRegProv -Name GetMultiStringValue -ArgumentList $hklm, $key, $($rc.sNames[$i]) | select -ExpandProperty sValue}            
       default {Write-Warning "Could not process $($rc.sNames[$i]) - type $($rc.Types[$i])"}            
     }            
            
     $data += @{$($rc.sNames[$i]) = $value}            
            
                   
  }  ## end for            
              
}            
else {            
 Write-Error "WMI call to registry provider failed"            
}              
            
$data.GetEnumerator() | sort key

 

I’ve cheated for now and defined the NIC I’m interested in – Index =7 is my LAN connection.

I need to work with the HKLM hive so define the appropriate constant.

After getting the WMI object for the NIC – filter on Index I use the SettingID to define the registry key I need. The settingID looks like this – {01F4E3B7-5F1F-40BD-8252-DCC3331891C1}

The EnumValues method gives me the registry value names and types for that key. I can loop through them and call the appropriate method to read the registry value.

The data is output sorted by value name and looks like this

Name                           Value

—-                           —–

AddressType                    0

DefaultGateway                 
DefaultGatewayMetric           
DhcpConnForceBroadcastFlag     0

DhcpGatewayHardware            {192, 168, 1, 1…}

DhcpGatewayHardwareCount       1

DhcpInterfaceOptions           {6, 0, 0, 0…}

DhcpServer                     255.255.255.255

Domain                                   
EnableDeadGWDetect             1

EnableDHCP                     0

IPAddress                      10.10.54.202

IsServerNapAware               0

Lease                          0

LeaseObtainedTime              1336923004

LeaseTerminatesTime            2147483647

NameServer                     10.10.54.201

RegisterAdapterName            0   
RegistrationEnabled            1   
SubnetMask                     255.255.255.0

T1                             1336923004

T2                             1336923004

UseZeroBroadcast               0  

 

This shows we have a static address – the fact that IPAddress is set and that EnableDHCP=0

Next time we will look at enabling DHCP and then setting the alternative configuration

TCP/IP Alternative Configuration: pt II Set DHCP

$
0
0

The next step on our journey to an alternative configuration is setting the NIC to use DHCP

I will keep cheating for now and specify the NIC – on my machine I now it is the NIC whose Win32_NetworkAdapterConfiguration has an Index of 7

$index = 7            
Get-WmiObject -Class Win32_NetworkAdapterConfiguration `
-Filter "Index=$index" |            
Invoke-WmiMethod -Name EnableDHCP

This sets the IP address to be obtained automatically via DHCP BUT it doesn’t set the DNS server to be delivered via DHCP. The old static DNS entries are retained.

To resolve this we use the SetDNSServerSearchOrder method without any arguments

$index = 7            
            
$nic = Get-WmiObject -Class Win32_NetworkAdapterConfiguration `
-Filter "Index=$index"             
            
Invoke-WmiMethod -InputObject $nic -Name EnableDHCP            
Invoke-WmiMethod -InputObject $nic -Name SetDNSServerSearchOrder            
            

I’ve modified the script slightly so we create an object for the WMI class and then use that object as the InputObject on two calls to Invoke-WmiMethod

We could have just as easily used

$nic.EnableDHCP()

$nic.SetDNSServerSearchOrder()

Now that we have the NIC set to use DHCP we need to configure the Alternative Configuration

More information on working with network adapters can be found in PowerShell and WMIwww.manning.com/powershellandwmi

TCP/IP Alternative Configurations: pt III set the alternative configuration

$
0
0

 

We have seen how to set the NIC to use DHCP to get its address. This post shows how to set the alternative configuration on the NIC. If you just  want APIPA then do nothing – other wise use this script

$HKLM = 2147483650 #HKEY_LOCAL_MACHINE            
            
$index = 7            
$nic = Get-WmiObject -Class Win32_NetworkAdapterConfiguration -Filter "Index=$index"            
            
$key = "SYSTEM\CurrentControlSet\services\Tcpip\Parameters\Interfaces\$($nic.SettingID)"            
            
Invoke-WmiMethod -Class StdRegprov -Name SetDWORDvalue -ArgumentList $hklm, $key, "AddressType", 2            
            
Invoke-WmiMethod -Class StdRegprov -Name SetMULTISTRINGvalue -ArgumentList $hklm, $key, "Alternate_$($nic.SettingID)", "ActiveConfigurations"            
Invoke-WmiMethod -Class StdRegprov -Name SetSTRINGvalue -ArgumentList $hklm, $key, "10.10.54.202", "DhcpIpAddress"            
Invoke-WmiMethod -Class StdRegprov -Name SetSTRINGvalue -ArgumentList $hklm, $key, "10.10.54.201", "DhcpNameServer"            
Invoke-WmiMethod -Class StdRegprov -Name SetSTRINGvalue -ArgumentList $hklm, $key, "255.255.255.0", "DhcpSubnetMask"

Again I’m cheating by defining the NIC in terms of its Index number

The registry key is derived from the SettingID property of the NIC

We then need to set a number of registry values. The AddressType sets the alternative configuration to use our informations rather than APIPA. The ActiveCinfigurations value is set using the SettingID property of the NIC

The address, subnetmask, and names server are set.

If you look carefully at the lines where we use the SetMULTISTRINGvalue and SetSTRINGvalue methods you will notice that we give the hive, key, value and then registry value name  whereas the SetDWORDvalue method we give hive, key, value name and then value.

This is a quirk of Invoke-WmiMethod

The WMI documentation for SetMULTISTRINGvalue and SetSTRINGvalue methods state the parameters should be:

  • hive
  • registry key
  • registry value name
  • value

This order is constant across the Set* methods of the StdRegProv class -  see http://msdn.microsoft.com/en-us/library/windows/desktop/aa393600(v=vs.85).aspx

If we do some investigation

PS> ([wmiclass]"StdRegprov").GetMethodParameters(‘SetSTRINGvalue’)


__GENUS          : 2

__CLASS          : __PARAMETERS

__SUPERCLASS     :

__DYNASTY        : __PARAMETERS

__RELPATH        :

__PROPERTY_COUNT : 4

__DERIVATION     : {}

__SERVER         :

__NAMESPACE      :

__PATH           :

hDefKey          : 2147483650

sSubKeyName      :

sValue           : hello

sValueName       :

This clearly shows we need to give the value before the value name.

the same holds true if we investigate using Get-CimClass in PowerShell v3

Get-CimClass -ClassName StdRegProv |

select -ExpandProperty CimClassMethods |

where Name -eq "SetStringValue" |

select -ExpandProperty Parameters

produces

Name                                         CimType Qualifiers

—-                                         ——- ———-

hDefKey                                      UInt32 {ID, IN}

sSubKeyName                                  String {ID, IN}

sValue                                       String {ID, in}

sValueName                                   String {ID, in}

if we use Invoke-CimMethod its not to much of a problem as we have to provide the value name and value pairs as a hash table we are not relying on argument order.

I’ll post an alternative listing using the CIM cmdlets another time

TCP/IP Alternative Configurations: pt IV reset to static address

$
0
0

At some stage we may need to reset our NIC back to having a static address

$index = 7            
            
$nic = Get-WmiObject -Class Win32_NetworkAdapterConfiguration `
-Filter "Index=$index"             
            
$ipaddress = @("10.10.54.202")            
$subnet = @("255.255.255.0")            
Invoke-WmiMethod -InputObject $nic -Name EnableStatic -ArgumentList $ipaddress, $subnet            
            
$dnsserver = "10.10.54.201"            
$nic.SetDNSServerSearchOrder($dnsserver)            
            
#Invoke-WmiMethod -InputObject $nic -Name SetDNSServerSearchOrder -ArgumentList $dnsserver

We get the configuration of the NIC and use the EnableStatic method to set the address and subnet

The SetDNSServerSearchOrder method is used to set the DNS server.

Notice I haven’t been able to use Invoke-WmiMethod at this point – I’ve had to call the method directly on the object. There appears to be an issue with the formatting of the DNS server addresses as Invoke-WmiMethod complains that the argument has to be an array.

This is under investigation.

More on using WMI with PowerShell can be found in PowerShell and WMI. Chapter 11 covers network adapters in detail.  More details from www.manning.com/powershellandwmi

Using Invoke-WmiMethod to set the DNS servers

$
0
0

In the last post I showed that there was an issue with the way the SetDNSServerSearchOrder of the Win32_NetworkAdapterConfiguration class worked

This would work

$nic = Get-WmiObject -Class Win32_NetworkAdapterConfiguration -Filter "Index=7"
$nic.SetDNSServerSearchOrder("10.10.54.201")

but using Invoke-WmiMethod failed

After discussions with Bartek Bielawski (PowerShell MVP) and a bit more digging I found that for multiple DNS servers this would work

$dnsserver = "10.10.54.201", "10.10.54.98"
Get-WmiObject -Class Win32_NetworkAdapterConfiguration  -Filter "Index=7" | Invoke-WmiMethod -Name SetDNSServerSearchOrder -ArgumentList (, $dnsserver)

Its necessary to create an array as the input argument  (, $variable) – its a unary array ie one element array

if you want to use just a single DNS server then you need to use the unary array trick twice – once when you create the variable and again when you use Invoke-wmimethod.  Messy but it works

$dnsserver = (,"10.10.54.201")
Get-WmiObject -Class Win32_NetworkAdapterConfiguration  -Filter "Index=7" | Invoke-WmiMethod -Name SetDNSServerSearchOrder -ArgumentList (, $dnsserver)

 

If you want to use the new CIM cmdlets in PowerShell v3 – its easy if you have multiple DNS servers

$dnsserver = "10.10.54.201", "10.10.54.98"
Get-CimInstance -ClassName Win32_NetworkAdapterConfiguration -Filter "Index=7" | Invoke-CimMethod -MethodName SetDNSServerSearchOrder -Arguments @{DNSServerSearchOrder = $dnsserver}

 

for a single one we just need to create a unary array on the Arguments parameter
$dnsserver = "10.10.54.201"
Get-CimInstance -ClassName Win32_NetworkAdapterConfiguration -Filter "Index=7" | Invoke-CimMethod -MethodName SetDNSServerSearchOrder -Arguments @{DNSServerSearchOrder = (,$dnsserver)}

 

This is not satisfactory because we have to adopt different techniques depending on the number of DNS servers we need to put into NIC property. This is NOT a PowerShell issue – it has to be a WMI issue because the IP address that we saw last time also takes an array and it was very happy with a single value.

Hopefully this is not something that will come up too often but be aware of these options when working with WMI methods


Toggling between LAN and Wireless

$
0
0

One of the questions in the recent Scripting Games involved toggling between a wireless and LAN connection. Only one was to be up at any one time.

This can be solved using WMI but becomes hugely simpler in Windows 8/2012 as we get a bunch of cmdlets for working with network adapters.

Using WMI

Get-WmiObject -Class Win32_NetworkAdapter | Measure-Object

I get 15 objects returned on my system – but I’m only interested in 2 of them!

Using the new functionality

PS> Get-NetAdapter | ft -a Name, ifIndex, Status

Name             ifIndex Status
—-             ——- ——
Virtual Wireless      21 Disabled
Virtual LAN           12 Up

This leads to a simple piece of code

Get-NetAdapter |
foreach {
  $nic = $_
  switch ($_.Status){
   "Up"        {Disable-NetAdapter -InputObject $nic -Confirm:$false}
   "Disabled"  {Enable-NetAdapter -InputObject $nic -Confirm:$false}

  }
}

Get the adapter, test its status and toggle to the other.

These cmdlets are in the NetAdapter module which is created using the cmdlets over objects techniques to utilise WMI classes in a much friendlier way. Remoting capabilities are supplied by CIMsessions

Windows 8 Networking cmdlets

$
0
0

Windows 8 brings PowerShell v3 and a whole bunch of PowerShell modules.  One such module is NETTCPIP and as the name suggests is about networking.

PowerShell v3 automatically loads modules for you so as soon as PowerShell opens try

PS> Get-NetIPConfiguration

InterfaceAlias       : Ethernet
InterfaceIndex       : 13
InterfaceDescription : NVIDIA nForce 10/100/1000 Mbps Ethernet
NetProfile.Name      : Unidentified network
IPv4Address          : 10.10.54.202
IPv6DefaultGateway   :
IPv4DefaultGateway   :
DNSServer            : fec0:0:0:ffff::1
                       fec0:0:0:ffff::2
                       fec0:0:0:ffff::3

InterfaceAlias       : WiFi
InterfaceIndex       : 12
InterfaceDescription : Qualcomm Atheros AR5007 802.11b/g WiFi Ada
NetProfile.Name      : TiscaliF23E11
IPv4Address          : 192.168.1.2
IPv6DefaultGateway   :
IPv4DefaultGateway   : 192.168.1.1
DNSServer            : 192.168.1.1

InterfaceAlias       : Bluetooth Network Connection
InterfaceIndex       : 30
InterfaceDescription : Bluetooth Device (Personal Area Network)
NetAdapter.Status    : Disconnected

One thing that you will need to do is to set up PowerShell remoting

PS> Enable-PSRemoting

WinRM Quick Configuration
Running command "Set-WSManQuickConfig" to enable remote management of this computer by using the Windows Remote
Management (WinRM) service.
This includes:
    1. Starting or restarting (if already started) the WinRM service
    2. Setting the WinRM service startup type to Automatic
    3. Creating a listener to accept requests on any IP address
    4. Enabling Windows Firewall inbound rule exceptions for WS-Management traffic (for http only).

Do you want to continue?
[Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help (default is "Y"): a

Set-WSManQuickConfig : <f:WSManFault xmlns:f="http://schemas.microsoft.com/wbem/wsman/1/wsmanfault" Code="2150859113"
Machine="localhost"><f:Message><f:ProviderFault provider="Config provider"
path="%systemroot%\system32\WsmSvc.dll"><f:WSManFault xmlns:f="
http://schemas.microsoft.com/wbem/wsman/1/wsmanfault"
Code="2150859113" Machine="RSLAPTOP01"><f:Message>WinRM firewall exception will not work since one of the network
connection types on this machine is set to Public. Change the network connection type to either Domain or Private and
try again. </f:Message></f:WSManFault></f:ProviderFault></f:Message></f:WSManFault>
At line:69 char:17
+                 Set-WSManQuickConfig -force
+                 ~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (:) [Set-WSManQuickConfig], InvalidOperationException
    + FullyQualifiedErrorId : WsManError,Microsoft.WSMan.Management.SetWSManQuickConfigCommand

The emphasis of Public is mine. We have a network connection type set to public. At this point I would normally be tearing my hair out because network connection types are the ultimate pain to modify. I have hated the things since Windows Vista. No more they are now a minor inconvenience.

Look in the module NetConnection for Get-NetConnectionProfile

PS> Get-NetConnectionProfile

Name             : Unidentified network
InterfaceAlias   : Ethernet
InterfaceIndex   : 13
NetworkCategory  : Public
IPv4Connectivity : NoTraffic
IPv6Connectivity : NoTraffic

Name             : TiscaliF23E11
InterfaceAlias   : WiFi
InterfaceIndex   : 12
NetworkCategory  : Private
IPv4Connectivity : Internet
IPv6Connectivity : NoTraffic

Now we can get to it modifying is easy

PS> Set-NetConnectionProfile -InterfaceIndex 13 -NetworkCategory Private
PS> Get-NetConnectionProfile

Name             : Unidentified network
InterfaceAlias   : Ethernet
InterfaceIndex   : 13
NetworkCategory  : Private
IPv4Connectivity : NoTraffic
IPv6Connectivity : NoTraffic

Name             : TiscaliF23E11
InterfaceAlias   : WiFi
InterfaceIndex   : 12
NetworkCategory  : Private
IPv4Connectivity : Internet
IPv6Connectivity : NoTraffic

And now you can enable PowerShell remoting

Best of all the change is WMI based.  The netconnection cmdlets are created as CDXML from WMI classes new to Windows 8. Get-NetIPConfiguration is also CDXML.

CDXML is cmdlets over objects – WMI classes wrapped in XML and presented as a module

see Chapters 18 & 19 of PowerShell and WMI for more details

Internet Connection

$
0
0

Can you find the network adapter on your machine that’s connected to the Internet? On a Windows 8/2012 machine its fairly simple:

PS> Get-NetConnectionProfile -IPv4Connectivity Internet

Name : NetworkName
InterfaceAlias : AdapterName
InterfaceIndex : 12
NetworkCategory : Private
IPv4Connectivity : Internet
IPv6Connectivity : LocalNetwork

What else can you discover?

The important information is the InterfaceIndex

Get-NetAdapter -InterfaceIndex 12

shows the NIC information such as name, MAC address and speed (similar to Win32_NetworkAdapter)

Get-NetAdapterAdvancedProperty -Name name

shows buffer data

Get-NetAdapterStatistics -Name name

shows transmitted data

Get-NetIPConfiguration -InterfaceIndex 12

pulls the IP configuration

This just scratches the surface to the networking modules in Windows 8/2012

The modules are based on new WMI classes for the most part so you won’t find them on legacy operating systems even with WMF 3 loaded.

Setting an IP address

$
0
0

I need to add an IP address to an adapter. I could use the GUI or WMI but with Windows 8/2012 and above I’ve got all of the nifty networking cmdlets to play with.

Lets start with finding the adapter to use

PS>Get-NetAdapter

will show all of the adapters. Unlike ipconfig it only shows real NICs – thats physical and virtual but not stuff like “Tunnel adapter Teredo Tunneling Pseudo-Interface”

The one I’m interested in is

Name ifIndex Status
—- ——- ——
Connections 21 Up

You can find the IP addresses associated with this NIC

PS>Get-NetIPAddress -InterfaceIndex 21 -AddressFamily IPv4

IPAddress : 10.0.50.100
InterfaceIndex : 21
InterfaceAlias : Connections
AddressFamily : IPv4
Type : Unicast
PrefixLength : 24
PrefixOrigin : Manual
SuffixOrigin : Manual
AddressState : Preferred
ValidLifetime : Infinite ([TimeSpan]::MaxValue)
PreferredLifetime : Infinite ([TimeSpan]::MaxValue)
SkipAsSource : False
PolicyStore : ActiveStore

To add the IP address use:

New-NetIPAddress -InterfaceIndex 21 -AddressFamily IPv4 -IPAddress 10.0.18.100 -PrefixLength 24

Job done.

If you have to do this on a regular basis you can script finding the adapter and setting the IP address in one pass

Mac Address

$
0
0

No not where you go for a burger!

I saw a post on the forum about getting the MAC address fro remote machines. The original post was using a fixed filter on NetConnectionID which assumes that all of your machines are configured equally. I think a better approach is to gather all the data

function get-macaddress {
[CmdletBinding()]
param(
[string]$computername = $env:COMPUTERNAME
)
Get-WmiObject -Class Win32_NetworkAdapter -ComputerName $computername -Filter “NetConnectionID LIKE ‘%’” |
select PSComputerName, Description, NetConnectionID, MACAddress

}

The WMI filter ensures that only adapters with a NetConnectionID are returned.

Once you have the data you can ensure your machines are configured the same

Windows PowerShell Networking Guide

Subnets and prefixes

$
0
0

Sounds a bit like an old time role playing game but is actually a useful piece of knowledge.

You can define a subnet mask in 2 ways. Either use the full mask e.g. 255.255.248.0 or define the number of bits in the mask e.gg 21 which is known as the prefixlength in the PowerShell networking cmdlets.

But can you relate a full subnet mask to the number of bits. Some are obvious but the others I need to work out.

Time for a quick PowerShell function:

function show-subnetmask{

foreach ($prefixlength in 8..30) {

switch ($prefixlength){

{$_ -gt 24}

{

$bin = (’1′ * ($prefixlength – 24)).PadRight(8, ’0′)

$o4 = [convert]::ToInt32($bin.Trim(),2)

$mask = “255.255.255.$o4″

break

}

{$_ -eq 24}

{

$mask = ’255.255.255.0′

break

}

{$_ -gt 16 -and $_ -lt 24}

{

$bin = (’1′ * ($prefixlength – 16)).PadRight(8, ’0′)

$o3 = [convert]::ToInt32($bin.Trim(),2)

$mask = “255.255.$o3.0″

break

}

{$_ -eq 16}

{

$mask = ’255.255.0.0′

break

}

{$_ -gt 8 -and $_ -lt 16}

{

$bin = (’1′ * ($prefixlength – 8)).PadRight(8, ’0′)

$o2 = [convert]::ToInt32($bin.Trim(),2)

$mask = “255.$o2.0.0″

break

}

{$_ -eq 8}

{

$mask = ’255.0.0.0′

break

}

default

{

$mask = ’0.0.0.0′

}

}

New-Object -TypeName psobject -Property @{

PrefixLength = $prefixlength

Subnetmask = $mask

}

}

}

 

Most people will be using subnets between 8 and 30 bits in length so start with that range and for each value work through the switch statement. If the value is 8,16 or 24 the subnet mask can be set directly. Otherwise it needs to be calculated. The calculations are the same – the difference is which octet of the subnet mask is affected.

For instance if the prefix length is between 16 and 24 (exclusive)

$bin = (’1′ * ($prefixlength – 16)).PadRight(8, ’0′)

$o3 = [convert]::ToInt32($bin.Trim(),2)

$mask = “255.255.$o3.0″

break

Convert the number to a binary representation – the amount you need to subtract depends on the octet with which you are working

Convert the binary to an integer and insert into the subnet mask string.

An object is output that has the subnet mask and prefix length as properties.

Put the function in a module on your module path and you’ll be able to use it as a quick lookup when you need to convert subnet masks to prefix lengths or vice versa

 


Working with Server Core–setting IP addresses

$
0
0

When you create a new Windows machine it defaults to using DHCP to get an IP address. While that is fine for client machines most people apply a static address to their servers. Up until Windows 2012 you had 2 choices – use the GUI or use PowerShell and WMI.

Server 2012 introduced a host of cmdlets for administering your network settings.  Setting an IP address is simple as this:

New-NetIPAddress -InterfaceIndex 12 -IPAddress ’10.10.55.101′ -AddressFamily IPv4 -PrefixLength 24

I haven’t used it but you can also set the default gateway which would make the command

New-NetIPAddress -InterfaceIndex 12 -IPAddress ’10.10.55.101′ -AddressFamily IPv4 -PrefixLength 24 -DefaultGateway ’10.10.55.01′

The DNS server addresses can be set like this

Set-DnsClientServerAddress -InterfaceIndex 12 -ServerAddresses ’10.10.55.100′

The cmdlets are from the NetTCPIP and DnsClient modules respectively.

THESE MODULES ARE ONLY AVAILABLE ON WINDOWS 8/2012 AND LATER.

Viewing all 16 articles
Browse latest View live


<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>