PowerShell Scripting with WMI Part 2

PowerShell Tutorial 11 – Part 2: Scripting with Windows Management Instrumentation (WMI) – Methods

Part 1 introduced us to WMI. We learned how to ‘find’ classes and examine their properties and methods. Hope you downloaded and familiarized yourself with WMI CIM Studio, as it is a great tool to have. We also learned how to find WMI Classes when working in PowerShell. Tutorial 11 Part 1 was about gathering data by enumerating properties within a WMI Class. In Part 2 of the PowerShell Tutorial for WMI, we are going to be using Methods to make changes in our environment. The example scripts make changes to the environment, I highly recommend running any script in a test environment before applying them in your production environment.

Working with Methods

Example 1.

Here’s where the fun begins… The Big Boss has come to your office after you have successfully implemented DHCP on your network. You figure he’s there to give you a “big” pat on the back and an even “bigger” raise (wishful thinking). The reality is, the desktop group is complaining because they don’t want to re-configure each workstation from static IP to DHCP. It’s not that they have an underlying hatred for DHCP, they just don’t want to physically visit all 4000 workstations to make the change – I don’t blame them… You look the Boss right in the eye and give him your standard answer, “NO PROBLEM” – I’ll take care of it. After all you are becoming a PowerShell GURU and you are no stranger to managing complex environments.

1. First step, what WMI Class are we going to use to accomplish this task? Using WMI CIM Studio, I did a search for “Network.” I found the Class “Win32_NetworkAdapterConfiguration” which has a method called “EnableDHCP” – Looks like a winner to me. Another important thing to note, this Class also has a property called “IPEnabled” which provides a boolean data type (True or False). The importance of this property will be apparent as we build the script.
2. I’m going test the script on my local workstation, so I verify that my NIC is setup as static:

PowerShell IP Address Config

DHCP Properties

3. Here is the script code that will change the NIC settings to “Obtain an IP address automatically”

$NICs = Get-WmiObject Win32_NetworkAdapterConfiguration `
| Where {$_.IPEnabled -eq “TRUE”}
foreach($NIC in $NICs) {$NIC.EnableDHCP()}

So what is the script doing?

  • The first line stores the results of our WMI query in a variable called $NICs.
  • It also utilizes the Property “IPEnabled” to filter active IP configured Network Adapters. This enables us to skip any disconnected, virtual, and/or non-IP configured NICs; such as NetBUI, IPX/SPX, AppleTalk, etc…
  • We then use a foreach loop to iterate each item in the collection and use the “EnableDCHP” method to configure the NIC as a DHCP client.
PowerShell Training - DHCP settings


You should see the following result:

PowerShell Training - IPCONFIG

ipconfig Results

4. Let’s verify we’ve received and IP address from DHCP. If you don’t have a DHCP server assigning addresses on your network, just follow the steps as we go. My address has changed from (my static IP range) to which is in my DHCP address pool, cool success! Okay… so we’re half way there with our code.

PowerShell Training - DNS Setting

DNS Changed to DHCP

5. The next step is to change the DNS setting to “Obtain DNS server address automatically.” We want to change this so that we can utilize the DNS Scope Options created on the DHCP server. This was not a simple feat in VBScript, as we could not pass a “NULL” or and Empty String as we did with EnableDHCP(). Using PowerShell we are able to pass a “NULL” to the SetDNSServerSearchOrder method which sets the DHCP option. We are only adding one line to our script code $NIC.SetDNSServerSearchOrder()

$NICs = Get-WMIObject Win32_NetworkAdapterConfiguration `
| where{$_.IPEnabled -eq “TRUE”}
Foreach($NIC in $NICs) {

Running the code should yield the following results:

Do an “ipconfig /all” to verify the DNS server settings as well as other scope options are available. You should also see DHCP Lease Obtain and Expires infomation.

Example 2.

I’m not going to leave you hanging, let’s say we want to use methods of the “Win32_NetworkAdapterConfiguration” Class to change to static IP or you wish to make changes in a static IP environment.

Let’s examine all the methods available to us:

Get-WmiObject Win32_NetworkAdapterConfiguration `
| Get-Member -MemberType Methods | Format-List

Here is a list of the Methods that are available to this Class:

  • DisableIPSec
  • EnableDHCP
  • EnableIPSec
  • EnableStatic
  • ReleaseDHCPLease
  • RenewDHCPLease
  • SetDNSDomain
  • SetDNSServerSearchOrder
  • SetDynamicDNSRegistration
  • SetGateways
  • SetIPConnectionMetric
  • SetIPXFrameTypeNetworkPairs
  • SetTcpipNetbios
  • SetWINSServer
  • ConvertFromDateTime
  • ConvertToDateTime
  • Delete
  • GetType
  • Put

Looking at the list, there are a number of methods we can use to remotely configure machines. Granted, the workstation is available on the network.

I’m going to share a script that is going to set the IP address, subnet mask, gateway, DNS, and WINS servers. But before I do a special note: Data Types, I bring it up again because knowing which “Data Type” is expected will help when using Methods. For example, let’s look at the Definitions for SetDynamicDNSRegistration and SetWINSServer Methods.

Name : SetDynamicDNSRegistration
Definition : System.Management…(System.Boolean FullDNSRegistrationEnabled…)

Right away you should notice that the Method uses a boolean argument (TRUE or FALSE). If you look at this setting graphically (Network Adapter properties – TCP/IP settings – Advanced Settings – DNS tab – Check box near the bottom) you will see that this setting is a check box. When checked the boolean value = TRUE, unchecked = FALSE.

In the real-world: A call comes in stating that a workstation was moved to another network subnet, when pinging its FQDN or doing a reverse DNS lookup it yields the old IP address. User can’t use application because network application requires name resolution (it can happen). You enumerate the “FullDNSRegistrationEnabled” property and it comes back with a setting of “FALSE.” Quickly you run the “FullDNSRegistrationEnabled(“TRUE”)” Method to resolve the issue. You’re a star!!!

Name :SetWINSServer
Definition: System.Management..(System.String WinsPrimaryServer, …)

Take note that this Method requires a text string data type. By now I’m sure we all know what a text string is.

Here is the script code:

$NICs = Get-WMIObject Win32_NetworkAdapterConfiguration `
| where{$_.IPEnabled -eq “TRUE”}
Foreach($NIC in $NICs) {
$NIC.EnableStatic(“”, “”)
$DNSServers = “”,”″
$NIC.SetWINSServer(“”, “”)
PowerShell Training - IP Static Config

Setting Static IP

IP Address, Subnet Mask, Default Gateway, DNS Servers configured

PowerShell Training - DNS Registration Enabled

Register Check Box Enabled

Register this connection’s addresses in DNS enabled.

PowerShell Training - WINS Configured

WINS Configuration

WINS Configured.

Let’s take a closer look at the code:

$NICs = Get-WMIObject Win32_NetworkAdapterConfiguration `
| where{$_.IPEnabled -eq “TRUE”}

The first line of code creates a variable called $NICs and holds all the properties and methods for the “Win32_NetworkAdapterConfiguration” Class “where” the Network Adapter is IP Enabled. The “where” filter allows us to choose only real network adapters apposed to virtual and/or non-IP based NICs.

Foreach($NIC in $NICs) {


We now use a “Foreach” loop to iterate the $NICs collection.

$NIC.EnableStatic(“”, “”)
$DNSServers = “”,”″
$NIC.SetWINSServer(“”, “”)

Within the foreach loop, we take an instance and use methods to assign values. Looking above we used the Method EnableStatic() to assign an IP address and subnet mask. Note: the IP address are integers but they have been encased in quotes as the Method requires a text string value. Also, each entry is separated by a comma.

$DNSServers = “”,”″

These two lines of code are interesting, as I ran into trouble with the “SetDNSServerSearchOrder” method. I attempted to use the following but it would only allow me to set the preferred DNS server – SetDNSServerSearchOrder(“”, “”)
I thought it would work the same as setting the WINS servers, but look at the differences in each method’s definition:
(System.String WINSPrimaryServer, System.String WINSSecondaryServer)

(System.String[] DNSServerSearchOrder)

Looking up the “SetDNSServerSearchOrder” method on the Microsoft Developer site it states:
The SetDNSServerSearchOrder WMI class method uses an array of string elements to set the server search order.

Okay… an array of string elements. We’ve worked with arrays, we know how to build them. Look at the code again:

$DNSServers = “”,”″

The first line creates an array and assigns values to the variable $DNSServers.
The second line uses the SetDNSServer… method and uses the values in $DNSServer.

Fun stuff right?!?
This is a good example of understanding which DataTypes are expected. Since I was puzzled by the definition, I looked up the Method on Microsoft Developers site and found the answer – phew!!!

Example 3.

In this example I’m going to show you how to format your hard drive… just kidding! But, if that were a task for you to complete, you should feel comfortable at this point with locating the WMI Class required and the Methods to do the job.

We are going to have a little fun, in this example were are going to use the “Win32_OperatingSystem” class to re-boot computers.

  1. Verify which Methods are available:
    Get-WmiObject Win32_OperatingSystem | Get-Member -MemberType Method | Format-List
  2. Available Methods:
    • Reboot
    • SetDateTime
    • Shutdown
    • Win32Shutdown

    Not much to it, we’ll use the “Reboot” Method to re-boot the computer. Don’t do it now, I’m just showing the code at this time.

  3. Local Re-boot code:
    $colItems = Get-WmiObject Win32_OperatingSystem
    Foreach($Item in $colItems){

    If you are a local Admin and you get the following error: “Privilege not held” there is a bug in .NET 1.0 SP3.

  4. The evil remote reboot. I just have to state this disclaimer: “Use this script only to resolve issues, do not use it to flame your fellow coworkers.” With that said, here is code to connected to a remote PCServer and reboot it. Save and run the code as RemBoot.ps1. The Code Prompts for the computer name you wish to reboot:
    $strComputer = Read-Host “Enter Computer Name”
    $colItems = Get-WmiObject Win32_OperatingSystem -ComputerName “$strComputer”
    Foreach($Item in $colItems) {

Okay… we could go on for days with examples on how to use Methods of a WMI Class. My goal of the WMI tutorials are to show you how to find Classes and discover which Properties and Methods are available. This is enough to get you up and working with WMI. There is also a really cool “FREE” tool for scripting with WMI (WMI Explorer) that comes from “ThePowerShellGuy” website. I’ve made the tool available in the new PowerShellPro Forums. Get It, you will love it!!!

In the Next tutorial we are going to talk about creating reports, and I get to rant about Microsoft (just a little). I’m also going to show you what I consider the proper PowerShell syntax for WMI…

Email This Page To A Friend Email This Page To A Friend

Be Sociable, Share!


By Matt Duguid on April 29th, 2008 at 9:10 pm

I am interested to see how to pass the IP ADDRESS and SUBNET in as powershell variables.

Do you mean something like this:

$ipaddress = “”
$subMask = “”
$NIC.EnableStatic($ipaddress, $subMask)

$ipaddress = Read-Host “Enter the IP Address”
$subMask = Read-Host “Enter Subnet Mask”
$GW = Read-Host “Enter Default Gateway”


By Christian BARDOU on June 27th, 2008 at 5:22 am

Hi Jesse ?,

In the “Foreach” loop of the example 2, i don’t understand how the IP address can be different for each instance of $NICs collection ?


The example provided assumes that only one nic in the system is IP enabled. Which is the case for a majority of workstations within most networking environments. If you have a special case where you have workstation that have multiple nics that require separate IP address, then you would set up a filter to connect to the nic of your choice. If you do a get-member on the wmi object there are many properties you can choose to filter. Since we are looking for a unique property I tend to use the MAC address of the nic. I want to change and customize the filter as follows:
$NICs = Get-WmiObject Win32_NetworkAdapterConfiguration `
| Where {$_.MACAddress -eq “3E:6D:10:34:22:3D”}

This filter assures me that I am connecting to the NIC I wish to make changes too. That way if I have two nics in the system, I’m only making changes to the one I choose…

By Palle Grassmé on December 10th, 2008 at 4:54 am

Is it possible to prepend the primary and secondary WINS server addresses to the existing WINS settings?

By Magnus Kristoffersen on March 10th, 2009 at 2:49 am

I have a script that is almost the same as your. (I’m searching for a spesific nic) So I was wondering if you had the same problem as me. After defining a gateway using SetGateways() the gateway i specify gets added as a default gateway that stays saved even after I turn on DHCP again. I cant figure out a way to remove it other than doing it manually.


Hi there..
I try a remote reboot script but I got a message like this:
“Get-WmiObject : Access is denied. (Exception from HRESULT: 0x80070005 (E_ACCESSDENIED))
At line:2 char:26
+ $colItems = Get-WmiObject <<<< Win32_OperatingSystem -ComputerName “$strComputer”
+ CategoryInfo : NotSpecified: (:) [Get-WmiObject], UnauthorizedAccessException
+ FullyQualifiedErrorId : System.UnauthorizedAccessException,Microsoft.PowerShell.Commands.GetWmiObjectCommand

You cannot call a method on a null-valued expression.
At line:4 char:13
+ $Item.Reboot <<<< ()
+ CategoryInfo : InvalidOperation: (Reboot:String) [], RuntimeException
+ FullyQualifiedErrorId : InvokeMethodOnNull”

Its looks like I dont have a permission,.. although I run a powershell as a administator user. Did I make something wrong to execute this script? any advice are welcome…

What if you need to have multiple IP addresses bound to the same NIC?

Tried the below but no success:

$NICs = Get-WMIObject Win32_NetworkAdapterConfiguration | where{$_.IPEnabled -eq “TRUE”}
Foreach($NIC in $NICs) {
$IPAddress = ”″,”″
$NIC.EnableStatic($IPAddress, “″)
$DNSServers = “″,”″,”″,”″
$NIC.SetWINSServer(”″, “″)

By Jack van Deur on April 3rd, 2011 at 10:05 pm


great info. I’m trying to write out the ip information from a form I created. But I got stuck on the Nammeserver info. Whatever I try it won’t accept the new settings. It tried:
$dnsserver = $textbox1.text,$textbox2.text
but that didn’t work. After that I tried explicitly declaring an array or strings, seperate string variables but nothing works. Can you helpon this one?

Thanks in advance.


The arrays should have an @ symbol before the values and parantheses around them, like this:

$DNSServers = @(“,” $NIC.SetDNSServerSearchOrder($DNSServers)

Once this is corrected, his code works.

Getting errors when submitting posts. My code above shouldn’t have any question marks but quotes and there was a carriage return after the first closed parantheses. LOL

I missed one other thing. For SetDynamicDNSRegistration, as it is, “TRUE” it doesn’t seem to work.


That works.

$NIC.SetDNSServerSearchOrder()doesnt seems to work.

Cannot find an overload for “SetDNSServerSearchOrder” and the argument count: “2”.

Hi, I have been looking for something this simple and it is amazing. I have 2 questions.

1) How do I run this on another computer using the invoke-command, or do I even need to use that.
2) On the script, do I even need to have the last 3 lines of code really – $NIC.SetDNSServerSearchOrder($DNSServers)
$NIC.SetWINSServer(”, “

I am brand new to all of this.

I do have something to add a little, it is a reboot/logoff/restart/shutdown for our other admins here to use at the office.

# pegasus = computer name
# sunnymuffin = command
# Commands:
# 0 – Log Off
# 4 – Forced Log Off
# 1 – Shutdown
# 5 – Forced Shutdown
# 2 – Reboot
# 6 – Forced Reboot
# 8 – Power Off
# 12 – Forced Power Off
# Show only the following – 4, 5, 6 – force logoff of user, force shutdown, 6 force reboot

$pegasus = read-host “Type the computername or ip address”

$sunnymuffin = read-host “Choose the following number:
4 – logoff user
5 – shutdown
6 – reboot”

(gwmi win32_operatingsystem -ComputerName $pegasus).Win32Shutdown($sunnymuffin)

thanks for putting this up!

I have two questions:

1) Foreach($NIC in $NICs) { } is always used in the article. What if I want to use a method on a particular object, what do I do then?

2) In the remote shut-down example, I am getting an “UnauthorizedAccessException”, how I can I fix that? =)


By rudy de vries on August 17th, 2011 at 1:44 am

you should use $true instead of “true”
because “false” equals also to boolean true ($false equals to boolean false)

hello sir,

pls,how i can change my ISP? from my provider?

my best regard

Hi all,

is it possible to change mask and gateway for multiple servers?

How do I run this powershell script to change dns and wins on remote systems? Like all of my servers?

Awesome Tutorial! Plain and simple, just the way it should be.

This is pretty straight forward. However, I am having problems making changes on windows 2008 boxes. Can anyone help

This script worked great on both a WinXP and Win7 box, except that it did not populate the WINS IP setting. What might be the cause for this?
I am testing this out on my workstations before unleashing on all of our network servers.
Also, is there away to get an output file that notes if the DNS/WINS was changed or not?

Any way you can use a variable for the
$DNSServers = “″,”″

section, i’e. Ask the user which location they are in and set the default DNS servers for that location?

When i try and run any of the changes in this script against a 2003 server i get
ReturnValue : 91
and no changes are made. I’m admin on the server so any ideas?

A few things would make this PERFECT!
1) READ FROM A FILE, containing a list of servers and workstations that need to be changed
2) Output successes, failures, etc. to a log file
3) And this is HUGE! *DISPLAY* the settings BEFORE you change them! That way, you have an added assurance
4) Display the settings AFTER the change

#3 & #4 can go to a report file or append to the aforementioned log, so you can audit the actual results

also, how i set ONLY the ‘subnet mask?’

above shows setting BOTH ip + subnet, but our IPs are okay, just need to modify ONLY the subnet mask.

any help greatly appreciated!

how do set ONLY the subnet mask?
it is not clear how to do that.
i don’t want 2 change IP addy, just MASK.

Hi, thanks for a great tutorial! I am new and still learning. From searching the NET for example codes and make it works for my env and it has been great.
Get-WMIObject Win32_NetworkAdapterConfiguration will give you the result of DNSSearchOrder in the array format: DNSServerSearchOrder : {,}
when I use this code to out put DNS servers to excel, it only output the 1st DNS server
the question is how can I output the 2nd DNS server IP address to excel?
this is how I get the NIC info:
$Networks = Get-WmiObject -credential $usrcred -class “Win32_NetworkAdapterConfiguration” -namespace “root\CIMV2” -ComputerName $strComputer | ? {$_.IPEnabled}

this is my code to output DNS servers to excel: $c.Cells.Item($intRow+11,$intcol) = $Network.DNSServerSearchOrder

$intRow+11,$intcol put the data to cell 12,2

here is the result in excel
DNS Server Primary

thanks for your helps

Great Tutorial.

I think I am missing something here. Is this code good for one computer only or is it used for the whole network? I would like to change all the IPs of all 150+ machines on my network how would I do that?

By Mandar Raibagi on May 21st, 2012 at 2:50 am

This is a great series of powershell with WMI tutorial. Please keep them coming!!!

By Bjorn Houben on June 22nd, 2012 at 4:23 am

As specified in the comments the following does not work: $NIC.SetDynamicDNSRegistration(“true”)

Even though suggested in the comments,this also does not work: $NIC.SetDynamicDNSRegistration($true)

What worked for me was:

Hope it helps someone.

By Lamsonckc on June 22nd, 2012 at 8:22 am

I want to change Static IP of 10 Computer by PS Script. Help me, Please!!!

By Jay Kulsh on July 12th, 2012 at 2:04 pm

MichaelB (Apr 27, 2012) made a valid point. The script has a major problem if you are running it against multiple machines. You don’t want all of them to have the same IP!

To run this against multiple target computers, you should use a hash table. You could even have the script read the IPs from an external TXT file, but start with something like this:

$ServerIPs = @{“Server1” = “”; “Server2” = “”; “Server3” = “”}
Foreach ($strComputer in $ServerIPs.Keys)
$strIPAddr = $ServerIPs.Item($strComputer)
“Computer Name = ” + $strComputer + ” – IP Address = “+ $strIPAddr

$NICs = Get-WMIObject Win32_NetworkAdapterConfiguration `
-ComputerName $strComputer | where{$_.IPEnabled -eq “TRUE”}
Foreach($NIC in $NICs) {
$DNSServers = “”,”″

If you really want to get fancy, maybe you have to configure servers across multiple subnets. You need to include the default GW address in the table. Just go multi-dimensional on the hash-table definition.

$ServerIPs = @{“Server1” = “”,”″,”″; `
“Server2” = “”,”″,”″; `
“Server3” = “”,”″,”″}

You can then retrieve the values using:
$strIPAddr = $ServerIPs.Item($strComputer)[0]
$strNetMask = $ServerIPs.Item($strComputer)[1]
$strGWAddr = $ServerIPs.Item($strComputer)[2]

For setting multiple IP addresses to a single NIC, you need to have a matching number of subnet masks in the $Subnet array.
Combine this with the hash tables described earlier and you have a pretty powerful script.

$ip = @(“”, “”, “”, “”, “”, “”)
$Subnet = @(“”, “”, “”, “”, “”, “”)
$adapterConfig.EnableStatic($ip, $Subnet)

Can we get the windows updates information (i.e. what are the pending updates to be installed on the machine or is the machine up to date) using this object.

How could i get a notification in email that windows OS clients doesn’t get the DHCP IP addresses from the DHCP server.
could you sahre the vb script on how the windows OS servers notify in email to SMTP server when they don’t any IP from DHCP server.

Anybody know how I can blank out the DNS servers. We have some private addresses, like PLC’s, where we switch IP’s on the fly on a laptop. DNS is not needed. I’ve tried $dnsservers=@(“”,””,””) with $NIC.SetDNSServerSearchOrder($DNSServers).
$dnsservers.length returns 3, so I assume I have 3 blank entries. I get back return code 70, so I assume sending it nulls isn’t the way to go.

To empty the DNS Search order use $NIC.SetDNSServerSearchOrder().

How do I pass reference of CIM class to methods?

For Eg: I want to invoke the below method whose parameter is CIM_LogicalPort class reference?

How can I invoke the below method whose parameter is CIM_LogicalPort class reference?


How can I invoke the below method whose parameter is CIM_LogicalPort class reference?

[METHOD NAME=”DeleteFiles” TYPE=”uint32″]

I’ve tried using the “enablestatic” method but keep getting a strange return value:

$NICs = Get-WmiObject Win32_NetworkAdapterConfiguration `
| Where {$_.IPEnabled -eq “TRUE”}
foreach($NIC in $NICs) {
$Nic.EnableStatic($ip, $subnet)

__GENUS : 2
__PATH :
ReturnValue : 2147786788
PSComputerName :

Any ideas? Thanks.

Great info here! thanks! I need to disable netbios on wireless and wired adapter, BUT if the observation is that if the adapter is not IP enabled nothing is setup. YET you can disable the netbios with GUI – any ideas?

$adapters = gwmi -ComputerName $env:computername Win32_NetworkAdapterConfiguration |? {$_.Description -match “Intel”}

$adapters | select description,Index,TcpIpNetbiosOptions,IPEnabled|ft -a

$adapters |%{$_.SetTcpipNetbios(2)}

I also tried to set the adapter to static IP and then disable it – but it still does not work

Just a quick question:

When I try using Enable.static it hangs. My understanding is that it works when it applies the changeIP to the target computer (Verfied by checking that PC/VM) but hangs because the IP change went through and the session loses it’s connection. Is there any work around for this?


By JULOWSKY on May 24th, 2014 at 8:16 am

This is most definitely some very useful syntax I have been trying to get down to include in an PowerShell-Module. It seems to never be consistent across hardware. Just wanted to reach out and say thank you to all of you for taking to the time to share your various examples and thoughts.

Great post! Thanks! I just couldn’t get any of the code to work. For example:

$NICs = Get-WMIObject Win32_NetworkAdapterConfiguration `
| where{$_.IPEnabled -eq “TRUE”}
Foreach($NIC in $NICs) {
$NIC.EnableStatic(“, “
$DNSServers = “,”
$NIC.SetWINSServer(“, “

Produced so many errors, that it was actually quicker to manually set all of these items up through the GUI than it was to read through the errors.

instead of using (which does not work!!!):

$DNSServers = “”,”″



Because u need an array!



should be


Hi All ,

i need a help on scripting , i l explain the scenario

i have physical server Windows 2012 , which is having 4 to 6 nic cards ,in that 2 of them for primary IP (have to do NIC teaming with that using windows 2012 nic teaming option) and one nic for Backup and one nic for NAS , we are not sure which is primary and which backup , we have to assign IP manually and check ping test then will get to know which is Primary , backup and NAS , so i want a script to assign IPs to respective NICs as well should done teaming …the script itself should detect which is primary and backup …is it possible

this is the script which i am trying …but working as expected….any idea

# saving the IP detials in Veriables

#$Primary = Read-host ” Please enter Pirmary IP ”
#$Subnet = Read-host ” Please enter Subnet Mask ”
#$gateway = Read-host ” Please enter Gateway ”
#$DNS1 = Read-host ” Please enter Primary DNS ”
#$DNS2 = Read-host ” Please enter Secondary DNS ”

# storing nics and Assign IPs to Nics

$NICs = Get-WMIObject Win32_NetworkAdapterConfiguration `
| where{$_.IPEnabled -eq “True” }

write-host “You have found ” $nics.Length ” nics”

Foreach($NIC in $NICs) {

$DNSServers = $DNS1,$DNS2

netsh int ip reset

# ping Nic
$pingResult = Test-Connection $gateway -count 4 -Quiet


if ($pingResult -eq $True)

# check if we alreadyy asssigned public1?’
if( $isServer1Found -eq $False){
$Public1 = $NIC
#Need to rename the NIC as Public1
$networkadapterID1 = gwmi win32_networkadapter | ? { $_.index -eq ($Public1).index}
Rename-NetAdapter -Name $networkadapterID1.NetConnectionID -NewName Public1 -PassThru

Write-Host ” nic1 found as Public1 “$NICs ” ”

# primary nic found so making it false
$isServer1Found = $True

elseif($isServer2Found -eq $false)

$isServer2Found = $True

# assigning nic to one varable $secondaryNic
$Public2 = $NIC
#Need to rename the NIC as Public2
$networkadapterID2 = gwmi win32_networkadapter | ? { $_.index -eq ($Public2).index}
Rename-NetAdapter -Name $networkadapterID2.NetConnectionID -NewName Public2 -PassThru


write-host “no things found ” $nics ” nics”


# Create Lbfo TEAM1, by binding “Ethernet” and “Ethernet 2” NICs.

New-NetLbfoTeam -Name TEAM1 -TeamMembers “Public1″,”Public2” -TeamingMode Lacp -LoadBalancingAlgorithm TransportPorts -Confirm:$false

# 20 second pause to allow TEAM1 to form and come online.

Start-Sleep -s 20

# Configure static IP Address, Subnet, Default Gateway, DNS Server IPs to newly formed TEAM1 interface.

New-NetIPAddress –InterfaceAlias “TEAM1” –IPAddress $Primary –PrefixLength 24 -DefaultGateway $gateway
Set-DnsClientServerAddress -InterfaceAlias “TEAM1” -ServerAddresses $dns1 , $dns2


Leave a Comment