Don't you hate it when you get to the office and discover you lost your house keys? You go desperately through all your pockets, but they are nowhere to be found. With a sigh, you are about to go digging through all the lost crannies in your bag when the boss pops in and reminds you that those application servers need their public-facing NICs moved to a new address space.
Avatar

Of course, you could always connect remotely to each and click about 85 times in each remote session multiplied by the number of servers and NICs. And that's assuming they're not running Server Core (Server Core is good for you; please use Server Core whenever you can). Given a large enough number of servers, your house would crumble to dust before you were done. And the keys would be useless at that point anyway, assuming you've found them in the meantime.

Or, you could work smart and use Windows Admin Center. We all know that nothing is faster than a web browser when it comes to making a lot of changes. No, I'm not dissing the WAC, but honestly, it is not quite the fastest way to do A LOT of changes.

Well, worry not. The function below helps you to update the IP address of a specific computer on a specific NIC. You can also disable DHCP and even clean up the old IP addresses from the DNS.

Let's look at the code and then we can go through some of the interesting details.

function Update-IPv4Address {
<# 
.SYNOPSIS
Update-IpAddress changes the IP of a NIC and deletes the old IP Address configured on that NIC. It can also disable DHCP (or not) for that interface and disable (or not) DNS registration.
.EXAMPLE
Update-IPv4Address -ComputerName Fs1 -InterfaceAlias Ethernet1 -NewIPv4Address 192.168.1.101 -PrefixLength 24 -DisableDhcp Yes -DisableDnsRegistration No -Verbose
Sets IP Address 192.168.1.101 on server Fs1, on NIC "Ethernet1." DHCP is disabled for the NIC, and DNS registration is enabled.
.EXAMPLE
Update-IPv4Address -ComputerName Node1 -InterfaceAlias "Ethernet #5" -NewIPv4Address 10.0.1.5 -PrefixLength 16
Sets IP Address 10.0.1.5/16 on server Node1, on NIC "Ethernet #5." DHCP is disabled for the NIC, and registration is enabled.
.EXAMPLE
Update-IPv4Address -ComputerName Server3 -InterfaceAlias "LAN2" -NewIPv4Address 192.168.5.5 -PrefixLength 24 -DisableDnsRegistration Yes
Sets IP Address 192.168.5.5/24 on server Server3, on the NIC "LAN2." DHCP is disabled for the NIC, and DNS registration is disabled.

#>

[CmdletBinding()]

Param(
[Parameter(Mandatory=$false)][string]$ComputerName = $env:COMPUTERNAME, # Name of the computer where the IP Address will be udpated
[Parameter(Mandatory=$true)][string]$InterfaceAlias, # Network Interface Card on which the IP Address will be updated
[Parameter(Mandatory=$true)][string]$NewIPv4Address, # New IP Address for the selected NIC
[Parameter(Mandatory=$true)][ValidateRange(2,30)][int]$PrefixLength, # Subnet Mask for the new IP Address
[Parameter(Mandatory=$false)][ValidateSet("Yes","No")][string]$DisableDhcp = "Yes", # Define whether DHCP is enabled for the NIC 
[Parameter(Mandatory=$false)][ValidateSet("No","Yes")][string]$DisableDnsRegistration = "No", # Define whether DNS registration is enabled for the NIC
[Parameter(Mandatory=$false)][string]$DnsServer # Name of the DNS server on which the new IP address will be updated and old addresses will be removed (if DNS registration is required). If a DNS server is not mentioned, the command will be run against the logon DC (which is usually a DNS server)
)

# If a Computer Name is not provided, the operation will be performed on the local computer.
if (!($ComputerName)) { Write-Verbose "A computer name was not specified. The operation will be performed on this computer" }

# If DisableDhcp is not specified, DHCP will be disabled by default for the NIC.
if (!($DisableDhcp)) { Write-Verbose "No option was specified for disabling DHCP. DHCP on the NIC $InterfaceAlias will be disabled automatically." }

# If DisableDnsRegistration is not specified, DNS Registration will be enabled by default for the NIC.
if (!($DisableDnsRegistration)) { Write-Verbose "No option was specified for DNS registration. DNS registration for the NIC $InterfaceAlias will be enabled automatically." }

# Test whether the computer is available for remote management. Abort if it cannot be reached.
if (!(Test-NetConnection -ComputerName $ComputerName -CommonTCPPort WINRM -InformationLevel Quiet)) {
    Write-Warning "The computer $ComputerName is not reachable. Make sure the computer name `"$ComputerName`" is correct and that the computer is reachable"
    break
    }

# Test whether the NIC is present on the $ComputerName. Abort if there is no NIC with the specified Name.
if (!(Get-NetAdapter -CimSession $ComputerName | where Name -EQ $InterfaceAlias)) {
    Write-Warning "The NIC $InterfaceAlias could not be found on  $ComputerName. Aborting the operation."
    break
    }

# If DNS registration is required for the NIC, check that the DNS server service is running on the $DnsServer (and abort if it is not).
if ($DisableDnsRegistration -eq "No") {
    if (!(Get-Module -ListAvailable DnsServer)) {
        Write-Warning "The function requires the module DNSServer in order to perform operations on a DNS server. Please install the Powershell Module for DNS Management and run the function again. The syntax for installing the DNS Server PowerShell Module is: Install-WindowsFeature -Name RSAT-DNS-Server"
        break
        }
  
    # If a DNS server is not specified, DNS operations will be attempted on the logon DC (DCs are usually DNS servers).
    if (!($DnsServer)) {
        $DnsServer = ($env:LOGONSERVER).Replace("\","")
        }
    # If the service is not running, the operation will be aborted.
    if (((Get-Service -ComputerName $DnsServer -ServiceName DNS -ErrorAction SilentlyContinue).Status) -ne "Running") {
        Write-Warning "You have selected to enable DNS registration for the NIC $InterfaceAlias but have not provided a valid DNS server. Please run the command again and specify a valid DNS server"
        break
        }
    }

# Get the current IPv4 address(es). These will be replaced with the new IP Address.
$OldIpv4Address = Get-NetIPAddress -CimSession $ComputerName -InterfaceAlias $InterfaceAlias -AddressFamily IPv4 

# Perform changes if the new IP address is different.
if ($NewIPv4Address -notin $OldIpv4Address.IPv4Address) {

    # Set the new IP address to the target on the NIC.
    Write-Verbose  "Adding the IP Address $NewIPv4Address to the NIC $InterfaceAlias on computer $ComputerName"
    New-NetIPAddress -CimSession $ComputerName  -InterfaceAlias $InterfaceAlias -AddressFamily IPv4 -IPAddress $NewIpv4Address -PrefixLength $PrefixLength -Type Unicast | Out-Null

    # Configure DNS and DNS registration, if required. Also register the client in DNS.
    if ($DisableDnsRegistration -eq "No") {
        
        # Notify that the function will attempt to use the logon DC for the local computer as DNS server.
        Write-Verbose  "No DNS server was specified. Will use the logon DC ($DnsServer) for the computer $env:COMPUTERNAME as DNS server" 
        
        # Get the IP Address(es) of the DNS server(s) from the local computer.
        $DnsServerIpAddress = (Get-WmiObject -Class Win32_NetworkAdapterConfiguration -Filter IPEnabled=TRUE | where DNSDomain -EQ $env:USERDNSDOMAIN).DNSServerSearchOrder
        
        # Get a list of entries in DNS for the old IP Address(es) for $ComputerName.
        $OldServerDnsEntries = Get-DnsServerResourceRecord -ComputerName $DnsServer -ZoneName "$env:USERDNSDOMAIN" -RRType A | Where-Object {$_.Hostname -like $ComputerName} | Select-Object HostName,@{Name="IpAddress";Expression={$_.RecordData.IPV4Address.IPAddressToString}}
        
        # Set the IP address(es) for the DNS Server(s) on the NIC.
        Write-Verbose  "Add the DNS server(s) $DnsServerIpAddress to the NIC $InterfaceAlias on computer $ComputerName"
        Set-DnsClientServerAddress -CimSession $ComputerName -InterfaceAlias $InterfaceAlias -ServerAddresses $DnsServerIpAddress
        
        # Enable DNS registration for the NIC.
        Write-Verbose  "Enable DNS registration for the interface $InterfaceAlias on $ComputerName"
        Set-DnsClient -CimSession $ComputerName -InterfaceAlias $InterfaceAlias -RegisterThisConnectionsAddress $true
        # Register the server in DNS.
        Register-DnsClient
        
        # Wait for the host to learn the new IP Address of the computer $ComputerName.
        Write-Verbose  "Waiting for this computer ($env:COMPUTERNAME) to learn the new IP Address of the computer $ComputerName..."

        # Wait for the new IP Address to appear in DNS.
        while ($NewIPv4Address -notin ((Resolve-DnsName -Name $ComputerName -Server $DnsServer).IPAddress)) {
            Clear-DnsClientCache
            Start-Sleep -Seconds 1 
            #$CheckIp = (Resolve-DnsName -Name $ComputerName -Server $DnsServer).IPAddress
            }
        }
    
    # Disable DNS registration, if required.
    else {
        Write-Verbose  "Disable DNS registration for the NIC $InterfaceAlias on $ComputerName"
        Set-DNSClient -CimSession $ComputerName -InterfaceAlias $InterfaceAlias –RegisterThisConnectionsAddress $False
        }

    # Disable DHCP, if required.
    if ($DisableDhcp -eq "Yes") {
        Write-Verbose  "Disabling DHCP for the interface $InterfaceAlias on $ComputerName"
        Set-NetIPInterface -CimSession $ComputerName  -InterfaceAlias $InterfaceAlias -AddressFamily IPv4 -Dhcp Disabled -ErrorAction SilentlyContinue
        }

    # Go through each of the old IP Addresses and remove them from DNS.
    foreach ($i in $OldIpv4Address) {
        # Clean up old IP address entries in DNS and on the NIC.
        if ($i.IPv4Address -in $OldServerDnsEntries.IpAddress) {
            Write-Verbose  "Removing IP Address $($i.IPv4Address) from DNS"
            Remove-DnsServerResourceRecord -ComputerName $DnsServer -ZoneName "$env:USERDNSDOMAIN" -RRType A -Name $ComputerName -RecordData $i.IPv4Address -Force -ErrorAction SilentlyContinue
            Start-Sleep -Seconds 1
            }
        }

    Clear-DnsClientCache
    # Remove the old IP Addresses from the interface.
    foreach ($i in $OldIpv4Address) {
        Write-Verbose  "Removing IP Address $($i.IPAddress) from NIC $InterfaceAlias on $ComputerName"
        Remove-NetIPAddress -CimSession $ComputerName -InterfaceAlias $InterfaceAlias -AddressFamily IPv4 -IPAddress $i.IPAddress -Confirm:$false
        }
    }
# If the new IP address is not different, display a notification that the address is the same.
else { 
    Write-Verbose  "The IP address provided is already set on the NIC `"$InterfaceAlias`" on computer $ComputerName. No change was made" 
    }
}

There are a few parameters the function expects you to provide:

  • First, a computer name. If none is provided, it will attempt to perform the changes on the local computer. The function is kind enough to mention this to you (if you selected Verbose mode).
  • Then, you will need to provide a new IP address. I'm quite proud of this function, but I'll be the first to admit it is not able to guess an IP address for you. I know, I know...
  • You can disable DHCP on the NIC by setting the parameter DisableDhcp. If you don't specify it, it will be disabled by default. Once again, the function is kind enough to inform you about this (still assuming you're running the function with the Verbose switch).
  • You can also disable DNS registration for the NIC. Normally, you wouldn't be interested in doing that on a "public-facing" NIC, but if the network interface will be used for management or as part of a cluster-traffic-only subnet, you may want to skip this. You need to specify this with the value "Yes;" otherwise, DNS registration will not be disabled. Once again, the function is kind enough to inform you about this.
  • A DNS server. This is where the function will attempt to connect and clean up the old IP address. If one is not provided, it will attempt to do this on the DC your computer is logged on to. Normally, the DCs are DNS servers, too. If they are not DNS servers in your environment, or you are not in an AD environment, well ... please do provide a DNS server. You're probably used to it by now, but ... yes, the function will inform you. Just make sure you've selected Verbose mode.

You can get more information by using Get-Help Update-IPv4Address.

(Hint: also try the switch -Examples).

Once you've provided all these bits of information, the function will attempt to connect to the target computer. As this will be done via WinRM, the function will check for connectivity on that port. You don't need ping for this, and you don't need to allow all inbound traffic in the Windows Firewall. You don't allow all inbound traffic through the Windows Firewall for your computers, do you? Do you? I know, I was just making sure. Good job. Anyway, WinRM is enabled by default on modern Windows Server versions. If you disabled it previously, you'll need to enable it, at least for the computer where you're doing this.

Anyway, if the computer is reachable, the function will check whether the new IP address isn't already configured on your target computer and on the target NIC. If it is, you'll be prompted about this, and the function will stop. Gently.

If the IP address is different, the function will perform the following:

  • Assign the new IP address to the specified NIC on the target computer.
  • Configure DNS registration (if instructed to do so).
  • Register the address in DNS.
  • Wait for the local computer (the computer from which you're running the function) to "learn" the new IP address of the target computer.
  • Disable DNS registration (if prompted to do so). Of course, if you omitted this or mentioned that you wanted DNS registration, this step will not be performed.
  • Remove the old IP address(es) from the specified NIC on the target computer. If Verbose mode is selected, you will be informed about these old addresses, too.
Remotely updating and IP address with Update IPv4Address

Remotely updating and IP address with Update IPv4Address

First, we look at the IP address of our target computer, DC1. (If you're interested in Get-IPAddressPretty, give us a shout and I'll create a quick post about it, too.) The NIC we're interested in has the current IP address 10.0.1.51.

Then, we use our shiny function to update the IP address of the NIC (creatively) named "TheOtherNic" to 10.0.1.101. Check the result and you'll see the new address assigned to the NIC.

Subscribe to 4sysops newsletter!

Finally, we update it again (this time to 10.0.1.102), using the Verbose switch. This will show more information about what the function does.

avatar
37 Comments
  1. Avatar
    checker33 3 years ago

    Hi, very helpful. But how can i wrap this , so use the function under domain administrator creds?

    • Avatar Author

      Hi, Checker33. Thank you for the feedback, I am glad you found this useful.

      Yes, you may include the function in a custom PowerShell Module that you can load manually or automatically in your PowerShell console, editor etc. If the previous sentence sounds intimidating, create a new file with the extension ".psm1" (like "MyCustomfunctions.psm1"). Paste the code from this post in the psm1 file, and save it. When you want to run the function, import the module (Import-Module 'C:\temp\MyCustomfunctions.psm1") and then the function will be available.

      You may also save as a normal PowerShell script file (PS1), and then reference it using the . (dot). Yes, the command begins with a dot followed by a space and then the path to the PS1 file.

      . "C:\temp\MyCustomfunctions.ps1"

      If you're interested in more details, I could write a post on how to do this (both manually or automatically).

      Cheers. Emanuel

  2. Avatar
    David H 3 years ago

    Would it be possible to have this script be performed by MAC Address from a list?  I am ultimate trying to update my DNS Server on about 200 PCs.  I have a script that updates the DNS for ALL the NICs in the PC, but I dont want it on the NICs that are on private networks, actually would love to disable DNS registration on those NICS as well .

    • Avatar Author

      Hi, David.

      If you have a list of servers and their NICs, you a command like below to rename the NICs you want to make changes to, and then run the function explained here based on that Interface Alias.

      Get-NetAdapter -CimSession ServerX | where MacAddress -Like AB-CD-EF* | Rename-NetAdapter -NewName "NoIpForYou"

      If you only want to disable DNS registration on certain Mac Addresses you already have, you could even ditch the function and do something like this:

       Set-DnsClient -InterfaceIndex $((Get-NetAdapter  -CimSession ServerY | where MacAddress -Like AB-CD-EF*).ifIndex) -RegisterThisConnectionsAddress $false

      avatar
  3. Avatar
    Jake 3 years ago

    Hey David,

     

    Great function, I'll gladly use this.  Just a quick note, it appears to be lacking a closing brace for your function?  I think I understand the contents enough to put it in the right place, just wanted to mention it.

    • Avatar Author

      Hello, Jake.

      By the looks of it, yes, you are right. The last bracket in the code is the closing one for the last else statement.

      As the function was working (I checked and tested it thoroughly), most likely the function's closing bracket was lost in the posting process. 🙂

      I don't have access to change it (or I don't think I do), I'll point this to someone that definitely has.

      Cheers for the heads-up!

      Em.

       

  4. Avatar
    Sal 2 years ago

    Odd, seems like the upper case F in $False (line 114), causes problems in my shell. Gives weird errors about missing braces or commas. Not sure why. Changing it to lower case f makes them go away. Thanks for the code btw.

    • Avatar Author
      Emanuel 2 years ago

      Hi, Sal.
      I’m surprised by the behaviour, I didn’t get such behaviour. PowerShell should be case insensitive (unless you’re very specific about it, in some cases).

      Cheers. Emanuel

      P.S. You’re welcome, I hope you found it useful.

  5. Avatar
    David Ashwell 2 years ago

    How does this script handle the Gateway? If a computer on DHCP starts off with a Gateway of 192.168.0.1, what specifies its Gateway after I assigned the computer a static IP Address? Is the computer supposed to automatically keep it’s previous Gateway?

    On my first test to another computer the Gateway was left blank after running this script. It previously had its Gateway assigned from DHCP.

    • Avatar Author

      Hi, David.
      You may quickly modify to retrieve the current Default Gateway for the NIC, and then add the switch -DefaultGateway to the command New-NetIpAddress to set the same Gateway as before
      https://docs.microsoft.com/en-us/powershell/module/nettcpip/new-netipaddress

      Cheers. Emanuel

      • Avatar
        Lee Roy Anthony 2 years ago

        Hi Emmanuel!

        Your codes are a godsend!

        Would it be possible for you to provide equivalent codes if we’re to apply these to virtual machines/VMs? Thank you!

        • Avatar Author

          Hi, Lee, Roy, and Anthony. 🙂

          I’m glad you find this useful. You can run this command just as well inside VMs, there’s no actual difference. Or is it something specific to VMs that you had in mind?

          • Avatar
            Lee Roy Anthony 2 years ago

            Hi Emanuel!

            Thank you for replying! Well, my situation is that I need to run your commands ‘outside’ the VM. Sorry for the newbie term (‘coz I’m exactly that – a newbie). Specifically, the Set-DNSClientServerAddress command. This command necessitates me to be ‘inside’ the VM so I can change it’s DNS IP address. I need to do this while I’m ‘outside’ the VM. In fact, I’m adding this line of code to a Powershell syntax that automates VM creation installed with a virtual hard drive (to also automate OS installation) plus setting up virtual network connection with a specific DNS server. The part with the DNS server that I have to specify for the VM is the tricky part for me.

  6. Avatar
    Lee Roy Anthony 2 years ago

    Hi Emanuel!

    Invoke-Command is now my new best friend!

    In fact, I’ll also be using it for a code to extract the value of InterfaceIndex (thru Get-Netadapter). But how do I get the value/s of the property/ies (like InterfaceIndex and InterfaceAlias) of Get-Netadapter and use it/them, say move the value/s to a variable/s?

    Thank you!

    • Avatar Author

      Hi, Lee Roy (and Anthony).

      You could do something like
      $info = Invoke-Command -ComputerName Dc01,FS03 -ScriptBlock {Get-NetAdapter}.
      to store the info in the variable $info.

      However, for Get-Netadapter you don’t need Invoke-Command. Get-Netadapter can get info from remote systems .
      $info = Get-NetAdapter -CimSession Dc01,FS03

      • Avatar
        Lee Roy Anthony 2 years ago

        Hi Emanuel!

        This is great help. However, how do I get the value of InterfaceIndex only? If my guess is correct, the code you provided will dump all of what’s contained in Get-NetAdapter.

        Thank you!

        • Avatar Author

          Hi.
          You can do it in several ways:

          (Get-NetAdapter).InterfaceIndex
          or save everything in a variable and then use it in a similar way.
          $Nics = Get-Netadapter
          $Nics.InterfaceIndex

          or

          Get-NetAdapter | Select-Object -ExpandProperty InterfaceIndex

          These approaches are applicable to pretty much all PowerShell commands, not really to this one in particular. If you’re new with PowerShell, getting comfortable with these concepts will be of great help. There are quite a few PowerShell courses on Pluralsight that could be a boost for you at this stage (pretty much anything from Jeff Hicks would be an excellent choice, but start with the “beginner” courses). Pluralsight is not free, but it’s completely worth the investment, and it’s roughly the cost of a Netflix subscription. 🙂
          (I’m not affiliated in any way with them, but it helped me and I learned a lot).
          Alternately, there are tons of free resources on YouTube and elsewhere. The only limit is your time. And your curiosity. 🙂

          • Avatar
            Lee Roy Anthony 2 years ago

            Hi Emanuel!

            Every answer I get is like a new window of knowledge! Thank you!

            I’ve actually used something similar to your 2nd suggestion. In fact, here’s my test code:

            Invoke-Command -VMName Win10VMTest004 -ScriptBlock {
            $InterfaceIndex = Get-NetAdapter | Select-Object InterfaceIndex
            $InterfaceAlias = Get-NetAdapter | Select-Object InterfaceAlias
            Write-Output $InterfaceAlias
            If ($InterfaceAlias -eq “Ethernet 2”)
            {
            $InterfaceIndex = $InterfaceIndex4Set
            Write-Output $InterfaceAlias, $InterfaceIndex4Set
            }}

            However, using the 1st write-output that I’ve placed to trace where the process flows through, I’ve found out that it doesn’t enter or satisfy the IF statement. It displayed this:

            InterfaceAlias PSComputerName RunspaceId
            ————– ————– ———-
            Ethernet 2 Win10VMTest004 ffd983d1-21bf-42af-b123-bb0ec402dd3f
            Ethernet Win10VMTest004 ffd983d1-21bf-42af-b123-bb0ec402dd3f

            I need to ‘catch’ Ethernet 2. Suspecting that the second value ‘Ethernet’ is overwriting the 1st value ‘Ethernet 2’, I’ve tested a code where the IF tries to catch ‘Ethernet’ only. To no avail.

            You’re right, YouTube videos will surely do a lot of help also.

            Thank you! Your replies are always very helpful and enlightening.

            • Avatar Author

              Check out the difference between
              Get-NetAdapter | Select-Object -ExpandProperty InterfaceAlias
              and
              Get-NetAdapter | Select-Object InterfaceAlias

              Do you catch the difference? That’s PowerShell-related, not Get-Netadapter related. 🙂

              You may also use (Get-NetAdapter).InterfaceAlias

              Cheers

  7. Avatar
    Lee Roy Anthony 2 years ago

    HI Emanuel!

    Thank you!!!

    With your expert guidance, I was able to come up with this:

    PS C:\Windows\system32> Invoke-Command -VMName Win10VMTest004 -ScriptBlock {
    $InterfaceIndex2 = Get-NetAdapter | Select-Object -ExpandProperty InterfaceIndex
    $InterfaceAlias2 = Get-NetAdapter | Select-Object -ExpandProperty InterfaceAlias
    If ($InterfaceAlias2 -eq “Ethernet 2”)
    {
    $InterfaceIndex4Set = $InterfaceIndex2
    Write-Output $InterfaceIndex4Set, $InterfaceAlias2
    }}
    cmdlet Invoke-Command at command pipeline position 1
    Supply values for the following parameters:
    7
    4
    Ethernet 2
    Ethernet

    PS C:\Windows\system32>

    What I need is to ‘do something’ once I catch InterfaceAlias value of Ethernet 2, and it’s basically using the InterfaceIndex value of ‘7’ somewhere down the road.

    So I have very obvious questions in here. Am I dealing with an array when I access the contents of Get-NetAdapter? How do I ‘capture’ the same ‘row’ of data once I get the ‘Ethernet 2’ value of InterfaceAlias? Sorry about my ignorance. I did COBOL programming and as you can see, my knowledge is pretty Jurassic at best. 😉

    Thank you again!

    • Avatar Author

      Well, if you have more than one NIC, then you have an array. To be honest, I’m not very sure about what you’re doing (like what is $InterfaceIndex4Set).

      I think before you get into deeper stuff it would help you greatly to get more comfortable with the basic workings of PowerShell. Otherwise you’d try to drive a Formula 1 car after you just got your driver’s license.

      Until then, even if you get something right (or it would seem to be right), then the result of your script might not be what it seems, and it could come back to haunt you. Usually that happens right before you plan to go on vacation, or immediately after. 🙂

  8. Avatar
    Lee Roy Anthony 2 years ago

    Hi Emanuel!

    You’re right. 🙂

    These codes are meant to simulate if I’ll be able to get the value of InterfaceIndex once I encounter a value of ‘Ethernet 2’ in InterfaceAlias. I’ve made $InterfaceIndex4Set just so I can ‘see’ what’s inside it, after the movement of whatever is inside of InterfaceIndex. However, the obvious obstacle for me is that InterfaceIndex keeps on giving out 2 values, which is ‘7’ and ‘4’. I only need the 1st value of ‘7’ to appear once the IF statement gets satisfied with an InterfaceAlias value of ‘Ethernet 2’.

    What I want to do is to get all InterfaceAlias ‘Ethernet 2’ (and nothing else) and then use it’s corresponding InterfaceIndex, which should also have one value only. But I always get 2 values.

    Thank you!

  9. Avatar
    Lee Roy Anthony 2 years ago

    Hi Emanuel!

    I finally got it!

    I just had to use Select-Object’s limiter command!

    PS C:\Windows\system32> Invoke-Command -VMName Win10VMTest004 -ScriptBlock {
    $InterfaceAlias2 = Get-NetAdapter | Select-Object -First 1 -ExpandProperty InterfaceAlias
    $InterfaceIndex2 = Get-NetAdapter | Select-Object -First 1 -ExpandProperty InterfaceIndex
    If ($InterfaceAlias2 -eq “Ethernet 2”)
    {
    $InterfaceIndex4Set = $InterfaceIndex2
    Write-Output $InterfaceIndex4Set, $InterfaceAlias2
    }}
    cmdlet Invoke-Command at command pipeline position 1
    Supply values for the following parameters:
    7
    Ethernet 2

    This solution I got just from browsing backwards to the basics!

    Thank you!!!

    • Avatar Author

      Good, finally! :))
      You could have also done
      Get-NetAdapter | where InterfaceAlias -like “Ethernet 2”
      or whatever the NIC Alias was.
      Or
      (Get-NetAdapter)[0].InterfaceAlias
      This one is less nice and a bit unpredictable, but it does the same thing.

      There are many ways to achieve something. In the long run, I’d suggest you pick an option that’s reasonably fast and easy to understand for a colleague that’s looking at a script (or you in 6 months, like Mr. Jeff Hicks always says).

  10. Avatar
    Lee Roy Anthony 2 years ago

    Hi Emanuel!

    While happily looking at what I’ve been learning, there’s this realization (and warning) that I’m forching the codes to just ‘stop’ at the 1st record/occurence of ‘Ethernet 2’. What if there’s more? What if the value ‘Ethernet 2’ appears on the 2nd, 3rd, so on…? How will I be able to capture it if it’s not on the 1st record? Meaning, how will I be able to capture ‘Ethernet 2’ in InterfaceAlias when/if I don’t know when it will appear?

    You’ve introduced me to string formatting in your latest reply. Thank you!

    • Avatar Author

      Well, I also introduced you to filtering. And I’d definitely use Where-Object instead of more convoluted syntax and arrays for that purpose.
      Those are great tools and just as essential for other purposed, but not for this. I mentioned them here just to show there are more ways to accomplish something. And I also mentioned there are more ways, and that you should use the most suitable one for each case. 🙂

  11. Avatar
    Lee Roy Anthony 2 years ago

    I meant ‘forcing the codes…’. Sorry for the typo.

  12. Avatar
    Lee Roy Anthony 2 years ago

    I meant ‘forcing the codes’. Sorry for the typo.

  13. Avatar
    Joe Vasquez 2 years ago

    Thanks for the code. Unfortunately, I tried it on some older OSes. Windows 7. I had great difficulty trying to find alias on that machine. Since it had an older powershell there was not a get-netadapter command. I finally found the alias using the wmic NIC command. It turned out to be Local Area Connection. However, the command did not work saying it could not find that alias. I spent a few hours trying to figure out why but to no avail. It was the only windows 7 device on the network but I was stubborn. Any suggestions? I just changed it manually but still curious.

    • Avatar Author

      Hi, Joe. You could try to install PowerShell 5.1 on Windows 7. Then you should have the cmdlet available. I say “should”, because… I haven’t tested on Win7. To be honest, I try to keep away from older OSes as much as possible…

      Some info is available here (including download links):
      https://docs.microsoft.com/en-us/powershell/scripting/windows-powershell/wmf/setup/install-configure

      I hope this helps. Cheers!

      • Avatar
        Joe Vasquez 2 years ago

        Thanks for the response. I deal with people that have lingering old OSes so I try to figure these out. Unfortunately, they have less memory on those things so it was easier remoting in and changing it manually. Just going to focus on Windows 10. Still curious why so hard to get an alias.

        • Avatar Author

          Hi, Joe.
          Unfortunately, I know from experience the feeling of clients with old stuff. Win7 is not even the worst offender. If I throw a stick I’d easily hit a couple of Win2003 Servers. I don’t have to maintain them (nobody is maintaining them, actually), but fortunately they’re for some other project, (physically) disconnected from mine.
          Anyway. The command should work in PS5.1 (or higher, if possible on Win7). I renamed a NIC to Local Area Network, and ran
          Get-NetAdapter | where InterfaceAlias -Like "Local*" | Format-List
          and it worked fine.

          Name : Local Area Network
          InterfaceDescription : Intel(R) Ethernet Connection (4) I219-LM
          InterfaceIndex : 17

  14. Avatar
    Lee Roy Anthony 1 year ago

    Hi Emanuel!

    Giving credit to you as my online ‘mentor’, I now have scripts on how to automate VM creation (complete with virtual hard drive and Win10 OS, and virtual network). Another one that I was able to create is a script that automates network configuration and internet settings configuration to enable internet access for the generated VMs. All thanks to you!

    Now as I went back in here, it seems like I’m not the only one having trouble with parameter availability across Powershell versions. We use Powershell 5.1 in here. Now I’m looking forward to create 2 programs/utilities out of the 2 scripts that I’ve mentioned above, complete with password verification before you can use said utilities. However, I’ve just found out that the parameters -MaskInput and -AsPlainText are only available in PowerShell 7.0.

    Admitting again that I’m a newbie in PowerShell coding, I wanted to create codes to verify equality of passwords being entered. If you have a more efficient syntax that is 5.1 friendly, that would be great! But my obvious question should be: What equivalent parameters can I use? Or is there a workaround set of syntax in 5.1 so I can convert to plain text string what has been stored in System.Security.SecureString (in readable or unencrypted form, of course).

    Good to be back in this forum! Hehehe!

    Thank you!

Leave a reply to Joe Vasquez Click here to cancel the reply

Please enclose code in pre tags

Your email address will not be published. Required fields are marked *

*

© 4sysops 2006 - 2023

CONTACT US

Please ask IT administration questions in the forums. Any other messages are welcome.

Sending

Log in with your credentials

or    

Forgot your details?

Create Account