Introduction

In lab environments, it’s often necessary to manually configure DNS settings on network adapters to ensure proper network functionality. PowerShell provides a powerful way to automate this process, making it easy to force DNS settings across multiple machines.

PowerShell Script to Force DNS Settings

The following PowerShell script detects the active network card and sets the DNS servers:

# Detect Active Network Card
$CarteUP = ""
$Cards = Get-NetAdapter
foreach ($Card in $Cards) {
    if (($Card.Status -eq "Up") -and ($Card.Name -notlike "*VMware*")) {
        if (($CarteUP -eq "") -or ($CarteUP -like "*wi")) {
            $CarteUP = $Card.Name
        }
    }
}

# Detect Index of the Active Network Card
$IndexCarte = ""
$indexCards = Get-NetIPInterface
foreach ($indexCard in $indexCards) {
    if (($indexCard.InterfaceAlias -eq "$CarteUP") -and ($indexCard.AddressFamily -eq "IPv4")) {
        $IndexCarte = $IndexCard.ifIndex
        $DHCPCarte = $IndexCard.DHCP
    }
}

# Set DNS Servers
$dnsServers = "8.8.8.8", "8.8.4.4"
Set-DnsClientServerAddress -InterfaceIndex $IndexCarte -ServerAddresses $dnsServers

# Output the new DNS settings
$dnsSettings = Get-DnsClientServerAddress -InterfaceIndex $IndexCarte
Write-Host "DNS servers for $CarteUP set to: $($dnsSettings.ServerAddresses)"

Script Explanation

  1. Detect Active Network Card: Retrieves the active network adapter that is not a VMware adapter.
  2. Detect Index of the Active Network Card: Finds the index of the active network card with IPv4 address family.
  3. Set DNS Servers: Configures the DNS servers to Google’s public DNS (8.8.8.8 and 8.8.4.4) for the active network card.
  4. Output the new DNS settings: Displays the new DNS server addresses for the active network card.

0 Comments

Leave a Reply

Avatar placeholder

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.