I want a script the change the current ipv4 dns of current wifi from automatic to some ip and an alternative, in windows 11
and another script change back to automatic
is it possible? I want only to execute a file, which probably requires admin privilege
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Yes, it is possible to create two scripts in Windows 11 to change the DNS settings of your current Wi-Fi connection. One script will set custom DNS servers (primary and alternative), and the other will revert the DNS settings back to "Automatic" (DHCP). These scripts can be written in PowerShell, which is a powerful scripting language available on Windows.
Key Considerations:
Administrator Privileges: Modifying network settings requires administrative privileges. The scripts will need to be executed with elevated permissions.
Wi-Fi Interface Identification: The scripts will identify the currently active Wi-Fi interface dynamically.
DNS Settings:
Script 1: Set custom DNS servers (e.g., 8.8.8.8 as primary and 8.8.4.4 as alternative).
Script 2: Revert DNS settings to "Automatic" (DHCP).
Script 1: Set Custom DNS Servers
This script sets the DNS servers to 8.8.8.8 (primary) and 8.8.4.4 (alternative).
# Set-CustomDNS.ps1
# Requires administrator privileges
if (-not ([Security.Principal.WindowsPrincipal] [Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator")) {
Write-Host "Please run this script as an administrator." -ForegroundColor Red
exit
}
# Get the active Wi-Fi interface
$wifiInterface = Get-NetAdapter | Where-Object { $_.Status -eq "Up" -and $_.InterfaceDescription -like "*Wi-Fi*" }
if ($wifiInterface) {
$interfaceAlias = $wifiInterface.InterfaceAlias
# Set custom DNS servers
Write-Host "Setting custom DNS servers for interface: $interfaceAlias"
Set-DnsClientDnsSettings -InterfaceAlias $interfaceAlias -ServerAddresses ("8.8.8.8", "8.8.4.4") -ResetConnectionSpecificSuffix -PassThru
Write-Host "DNS servers set successfully: Primary = 8.8.8.8, Alternative = 8.8.4.4" -ForegroundColor Green
} else {
Write-Host "No active Wi-Fi interface found." -ForegroundColor Yellow
}
Script 2: Revert DNS Settings to Automatic
This script reverts the DNS settings back to "Automatic" (DHCP).
# Reset-DNS.ps1
# Requires administrator privileges
if (-not ([Security.Principal.WindowsPrincipal] [Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator")) {
Write-Host "Please run this script as an administrator." -ForegroundColor Red
exit
}
# Get the active Wi-Fi interface
$wifiInterface = Get-NetAdapter | Where-Object { $_.Status -eq "Up" -and $_.InterfaceDescription -like "*Wi-Fi*" }
if ($wifiInterface) {
$interfaceAlias = $wifiInterface.InterfaceAlias
# Reset DNS settings to Automatic (DHCP)
Write-Host "Resetting DNS settings to Automatic for interface: $interfaceAlias"
Set-DnsClientDnsSettings -InterfaceAlias $interfaceAlias -ResetConnectionSpecificSuffix -ResetServerAddresses -PassThru
Write-Host "DNS settings reverted to Automatic successfully." -ForegroundColor Green
} else {
Write-Host "No active Wi-Fi interface found." -ForegroundColor Yellow
}
Steps to Use the Scripts:
Create the Scripts:
Open Notepad or any text editor.
Copy and paste the respective scripts into separate files.
Save the files with .ps1 extensions, e.g., Set-CustomDNS.ps1 and Reset-DNS.ps1.
Run the Scripts:
Right-click on the .ps1 file and select "Run with PowerShell".
If prompted by User Account Control (UAC), click "Yes" to grant administrator privileges.
Optional: Create Executable Files:
To make it easier to execute the scripts, you can create batch files (.bat) that call the PowerShell scripts.
Example for Set-CustomDNS.bat:
@echo off
PowerShell -ExecutionPolicy Bypass -File "C:\Path\To\Set-CustomDNS.ps1"
pause
Example for Reset-DNS.bat:
@echo off
PowerShell -ExecutionPolicy Bypass -File "C:\Path\To\Reset-DNS.ps1"
pause
Place the Scripts in a Secure Location:
Store the scripts in a directory where they can be easily accessed, such as C:\Scripts.
Notes:
Execution Policy: By default, PowerShell restricts running scripts. The -ExecutionPolicy Bypass flag in the batch files temporarily allows the scripts to run.
Custom DNS Servers: Modify the IP addresses (8.8.8.8 and 8.8.4.4) in Set-CustomDNS.ps1 if you want to use different DNS servers.
Error Handling: The scripts include basic error handling to notify you if no active Wi-Fi interface is found.
Final Answer:
Yes, it is possible to create scripts to change and reset DNS settings on Windows 11. The provided PowerShell scripts (Set-CustomDNS.ps1 and Reset-DNS.ps1) achieve this functionality, and they can be executed directly or via batch files for convenience.
User
alright make both in one file and 2 options 1 set 2 unset
Assistant
Certainly! You can combine both functionalities (setting custom DNS and reverting to automatic) into a single PowerShell script with a menu-driven interface. This way, you can choose between the two options when you run the script.
Here’s how you can create a single script with two options:
Combined Script: DNS-Manager.ps1
# DNS-Manager.ps1
# Requires administrator privileges
if (-not ([Security.Principal.WindowsPrincipal] [Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator")) {
Write-Host "Please run this script as an administrator." -ForegroundColor Red
exit
}
# Function to set custom DNS servers
function Set-CustomDNS {
# Get the active Wi-Fi interface
$wifiInterface = Get-NetAdapter | Where-Object { $_.Status -eq "Up" -and $_.InterfaceDescription -like "*Wi-Fi*" }
if ($wifiInterface) {
$interfaceAlias = $wifiInterface.InterfaceAlias
# Set custom DNS servers
Write-Host "Setting custom DNS servers for interface: $interfaceAlias"
Set-DnsClientDnsSettings -InterfaceAlias $interfaceAlias -ServerAddresses ("8.8.8.8", "8.8.4.4") -ResetConnectionSpecificSuffix -PassThru
Write-Host "DNS servers set successfully: Primary = 8.8.8.8, Alternative = 8.8.4.4" -ForegroundColor Green
} else {
Write-Host "No active Wi-Fi interface found." -ForegroundColor Yellow
}
}
# Function to reset DNS settings to Automatic (DHCP)
function Reset-DNS {
# Get the active Wi-Fi interface
$wifiInterface = Get-NetAdapter | Where-Object { $_.Status -eq "Up" -and $_.InterfaceDescription -like "*Wi-Fi*" }
if ($wifiInterface) {
$interfaceAlias = $wifiInterface.InterfaceAlias
# Reset DNS settings to Automatic (DHCP)
Write-Host "Resetting DNS settings to Automatic for interface: $interfaceAlias"
Set-DnsClientDnsSettings -InterfaceAlias $interfaceAlias -ResetConnectionSpecificSuffix -ResetServerAddresses -PassThru
Write-Host "DNS settings reverted to Automatic successfully." -ForegroundColor Green
} else {
Write-Host "No active Wi-Fi interface found." -ForegroundColor Yellow
}
}
# Main menu
Write-Host "DNS Manager Script" -ForegroundColor Cyan
Write-Host "1. Set Custom DNS (8.8.8.8, 8.8.4.4)"
Write-Host "2. Reset DNS to Automatic (DHCP)"
Write-Host "3. Exit"
# Prompt user for choice
$choice = Read-Host "Enter your choice (1/2/3)"
switch ($choice) {
1 { Set-CustomDNS }
2 { Reset-DNS }
3 { Write-Host "Exiting..." -ForegroundColor Yellow; exit }
default { Write-Host "Invalid choice. Exiting..." -ForegroundColor Red }
}
How It Works:
Menu Options:
Option 1: Sets custom DNS servers (8.8.8.8 as primary and 8.8.4.4 as alternative).
User
give powershell code
Assistant
Here is the PowerShell code for the combined script that allows you to set custom DNS servers or reset DNS settings to automatic. This script includes a menu-driven interface with two options:
Combined PowerShell Script: DNS-Manager.ps1
# DNS-Manager.ps1
# Check for administrator privileges
if (-not ([Security.Principal.WindowsPrincipal] [Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator")) {
Write-Host "Please run this script as an administrator." -ForegroundColor Red
exit
}
# Function to set custom DNS servers
function Set-CustomDNS {
# Get the active Wi-Fi interface
$wifiInterface = Get-NetAdapter | Where-Object { $_.Status -eq "Up" -and $_.InterfaceDescription -like "*Wi-Fi*" }
if ($wifiInterface) {
$interfaceAlias = $wifiInterface.InterfaceAlias
# Set custom DNS servers
Write-Host "Setting custom DNS servers for interface: $interfaceAlias"
Set-DnsClientDnsSettings -InterfaceAlias $interfaceAlias -ServerAddresses ("8.8.8.8", "8.8.4.4") -ResetConnectionSpecificSuffix -PassThru
Write-Host "DNS servers set successfully: Primary = 8.8.8.8, Alternative = 8.8.4.4" -ForegroundColor Green
} else {
Write-Host "No active Wi-Fi interface found." -ForegroundColor Yellow
}
}
# Function to reset DNS settings to Automatic (DHCP)
function Reset-DNS {
# Get the active Wi-Fi interface
$wifiInterface = Get-NetAdapter | Where-Object { $_.Status -eq "Up" -and $_.InterfaceDescription -like "*Wi-Fi*" }
if ($wifiInterface) {
$interfaceAlias = $wifiInterface.InterfaceAlias
# Reset DNS settings to Automatic (DHCP)
Write-Host "Resetting DNS settings to Automatic for interface: $interfaceAlias"
Set-DnsClientDnsSettings -InterfaceAlias $interfaceAlias -ResetConnectionSpecificSuffix -ResetServerAddresses -PassThru
Write-Host "DNS settings reverted to Automatic successfully." -ForegroundColor Green
} else {
Write-Host "No active Wi-Fi interface found." -ForegroundColor Yellow
}
}
# Main menu
Write-Host "DNS Manager Script" -ForegroundColor Cyan
Write-Host "1. Set Custom DNS (8.8.8.8, 8.8.4.4)"
Write-Host "2. Reset DNS to Automatic (DHCP)"
Write-Host "3. Exit"
# Prompt user for choice
$choice = Read-Host "Enter your choice (1/2/3)"
switch ($choice) {
1 { Set-CustomDNS }
2 { Reset-DNS }
3 { Write-Host "Exiting..." -ForegroundColor Yellow; exit }
default { Write-Host "Invalid choice. Exiting..." -ForegroundColor Red }
}
How It Works:
Administrator Privileges:
The script checks if it is running with administrative privileges and exits if not.
Dynamic Interface Detection:
It identifies the currently active Wi-Fi interface using .
User
where and what wifi name I should set?
Assistant
You don't need to manually specify the Wi-Fi network name (SSID) in the script. Instead, the script dynamically identifies the currently active Wi-Fi interface based on its status (Status -eq "Up") and description (InterfaceDescription -like "*Wi-Fi*"). This ensures that the script works regardless of the specific Wi-Fi network you're connected to.
Here’s how it works:
How the Script Identifies the Active Wi-Fi Interface:
Dynamic Detection:
The script uses the Get-NetAdapter cmdlet to retrieve all network adapters.
It filters for adapters that are:
Currently active (Status -eq "Up").
Related to Wi-Fi (InterfaceDescription -like "*Wi-Fi*").
No Hardcoding Required:
You don’t need to hardcode the Wi-Fi network name (SSID) or adapter name because the script dynamically detects the active Wi-Fi interface.
Example Output of Get-NetAdapter:
Running Get-NetAdapter in PowerShell might produce output like this:
Name InterfaceDescription Status
---- -------------------- ------
Wi-Fi Intel(R) Wi-Fi 6 AX201 Up
Ethernet Realtek PCIe GbE Family Controller Down
In this case, the script will identify the Wi-Fi adapter because its Status is Up.
What Happens If No Wi-Fi Is Active?
If no active Wi-Fi interface is found (e.g., you're not connected to any Wi-Fi network), the script will display a message like this:
No active Wi-Fi interface found.
This ensures the script doesn't attempt to modify settings on an inactive or non-existent interface.
Where Do You Set the DNS Settings?
The DNS settings are applied to the active Wi-Fi interface identified by the script. You don’t need to specify the Wi-Fi name or SSID manually. Here’s how it works:
Custom DNS Servers:
When you choose option 1, the script sets the DNS servers (8.8.8.8 and 8.8.4.4) for the active Wi-Fi interface.
:
User
when I right click and open it with powershell, it starts a windows and gets closed immediately
Assistant
The issue you're experiencing occurs because PowerShell scripts (.ps1) execute and then immediately close the window after completion. This behavior is normal unless you include a mechanism to keep the window open (e.g., by pausing the script or running it in an interactive session).
To address this, you can modify the script or adjust how you run it. Below are several solutions to resolve the issue:
Solution 1: Run the Script from an Existing PowerShell Window
Instead of right-clicking and opening the script directly, you can run it from an already-open PowerShell window. This keeps the window open so you can see the output.
Steps:
Open PowerShell as Administrator:
Press Win + S, type PowerShell, right-click on "Windows PowerShell," and select "Run as administrator."
Navigate to the Script Directory:
Use the cd command to navigate to the folder where your script is saved. For example:
cd C:\Path\To\Script
Run the Script:
Execute the script using the following command:
.\DNS-Manager.ps1
Follow the Menu:
The script will display the menu, and the PowerShell window will remain open for you to interact with.
Solution 2: Add a Pause to the Script
You can modify the script to pause before exiting, allowing you to see the output.
Updated Script with a Pause:
Add the following line at the end of the script:
Read-Host "Press Enter to exit"
This will prompt the user to press Enter before the script closes the window.
Here’s how the updated script looks:
# DNS-Manager.ps1
# Check for administrator privileges
if (-not ([Security.Principal.WindowsPrincipal] [Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator")) {
Write-Host "Please run this script as an administrator." -ForegroundColor Red
Read-Host "Press Enter to exit"
exit
}
# Function to set custom DNS servers
function Set-CustomDNS {
# Get the active Wi-Fi interface
$wifiInterface = Get-NetAdapter | Where-Object { $_.Status -eq "Up" -and $_.InterfaceDescription -like "*Wi-Fi*" }
if ($wifiInterface) {
$interfaceAlias = $wifiInterface.InterfaceAlias
# Set custom DNS servers
Write-Host "Setting custom DNS servers for interface: $interfaceAlias"
Set-DnsClientDnsSettings -InterfaceAlias $interfaceAlias -ServerAddresses ("8.8.8.8", "8.8.4.4") -ResetConnectionSpecificSuffix -PassThru
Write-Host "DNS servers set successfully: Primary = 8.8.8.8, Alternative = 8.8.4.4" -ForegroundColor Green
} else {
Write-Host "No active Wi-Fi interface found." -ForegroundColor Yellow
}
}
# Function to reset DNS settings to Automatic (DHCP)
function Reset-DNS {
# Get the active Wi-Fi interface
$wifiInterface = Get-NetAdapter | Where-Object { $_.Status -eq "Up" -and $_.InterfaceDescription -like "*Wi-Fi*" }
if ($wifiInterface) {
$interfaceAlias = $wifiInterface.InterfaceAlias
# Reset DNS settings to Automatic (DHCP)
Write-Host "Resetting DNS settings to Automatic for interface: $interfaceAlias"
Set-DnsClientDnsSettings -InterfaceAlias $interfaceAlias -ResetConnectionSpecificSuffix -ResetServerAddresses -PassThru
Write-Host "DNS settings reverted to Automatic successfully." -ForegroundColor Green
} else {
Write-Host "No active Wi-Fi interface found." -ForegroundColor Yellow
}
}
# Main menu
Write-Host "DNS Manager Script" -ForegroundColor Cyan
Write-Host "1. Set Custom DNS (8.8.8.8, 8.8.4.4)"
Write-Host "2. Reset DNS to Automatic (DHCP)"
Write-Host "3. Exit"
# Prompt user for choice
$choice = Read-Host "Enter your choice (1/2/3)"
switch ($choice) {
1 { Set-CustomDNS }
2 { Reset-DNS }
3 { Write-Host "Exiting..." -ForegroundColor Yellow; exit }
default { Write-Host "Invalid choice. Exiting..." -ForegroundColor Red }
}
# Pause before exiting
Read-Host "Press Enter to exit"
User
I didn't get my wifi adapter name is Wi-Fi 66 should I replace *Wi-Fi* with *Wi-Fi 66*?
Assistant
No, you do not need to replace *Wi-Fi* with *Wi-Fi 66* in the script. The script is designed to dynamically detect your Wi-Fi adapter based on its description, and the *Wi-Fi* pattern is a wildcard that matches any adapter description containing the word "Wi-Fi." This means it will work for adapters like Wi-Fi, Wi-Fi 66, or even Intel(R) Wi-Fi 6 AX201.
Here’s why:
How the Script Detects the Wi-Fi Adapter
The script uses the following line to find the active Wi-Fi adapter:
Get-NetAdapter: Retrieves all network adapters on your system.
Where-Object { $_.Status -eq "Up" }: Filters for adapters that are currently active (status is "Up").
-like "*Wi-Fi*": Matches any adapter whose InterfaceDescription contains the word "Wi-Fi."
This approach ensures that the script works regardless of the exact name of your Wi-Fi adapter.
What If Your Adapter Name Is Different?
If your Wi-Fi adapter's InterfaceDescription does not contain the word "Wi-Fi," you can modify the filter to match your specific adapter. For example:
If your adapter description is Wi-Fi 66, the current *Wi-Fi* pattern will still match it because it contains "Wi-Fi."
If your adapter description is something completely different (e.g., Wireless Network Connection), you would need to adjust the filter.
How to Check Your Adapter Description
To confirm the exact InterfaceDescription of your Wi-Fi adapter, follow these steps:
Open PowerShell as Administrator.
Run the following command:
Get-NetAdapter | Select-Object Name, InterfaceDescription, Status
Look for the adapter with Status equal to Up and identify its InterfaceDescription. For example:
Name InterfaceDescription Status
---- -------------------- ------
Wi-Fi 66 Intel(R) Wi-Fi 6 AX201 Up
Ethernet Realtek PCIe GbE Family Controller Down
User
it gives No active WiFi adapter found.
Assistant
If the script is giving the error No active Wi-Fi adapter found, it means the script is unable to detect an active Wi-Fi interface. This issue can arise due to several reasons, such as:
Wi-Fi Adapter Not Active: Your Wi-Fi adapter might not be connected to a network or might be disabled.
Incorrect Filter: The InterfaceDescription of your Wi-Fi adapter might not match the filter (*Wi-Fi*).
Driver Issues: Your Wi-Fi adapter drivers might not be functioning correctly.
Virtual Adapters: Virtual adapters (e.g., for VPNs or virtual machines) might interfere with detection.
Let’s troubleshoot and resolve this step by step.
Step 1: Verify the Wi-Fi Adapter Status
Run the following command in PowerShell to check the status of all network adapters:
Get-NetAdapter | Select-Object Name, InterfaceDescription, Status
Look for:
An adapter with Status equal to Up.
An InterfaceDescription that corresponds to your Wi-Fi adapter (e.g., Intel(R) Wi-Fi 6 AX201, Wi-Fi 66, etc.).
Example output:
Name InterfaceDescription Status
---- -------------------- ------
Wi-Fi Intel(R) Wi-Fi 6 AX201 Up
Ethernet Realtek PCIe GbE Family Controller Down
If your Wi-Fi adapter is not listed or its Status is not Up, proceed to Step 2.
Step 2: Ensure Wi-Fi Is Enabled
Make sure your Wi-Fi adapter is enabled and connected to a network:
Press Win + I to open Settings.
Go to Network & Internet > Wi-Fi.
Ensure Wi-Fi is turned on and you are connected to a network.
Alternatively, use PowerShell to enable the Wi-Fi adapter:
Enable-NetAdapter -Name "Wi-Fi" -Confirm:$false
Replace "Wi-Fi" with the actual name of your Wi-Fi adapter if it’s different (e.g., "Wi-Fi 66").
Step 3: Check the Adapter Description
If your Wi-Fi adapter is active but the script still doesn’t detect it, the issue might be with the filter (). Run the following command to see the exact :
User
alright can I get it with $interface = Get-NetAdapter | Where-Object { $_.InterfaceIndex -eq <YOUR_INTERFACE_INDEX> } and print its adapter name with name not to miss spacing around. are the names striped?
Assistant
Yes, you can use the InterfaceIndex property to identify your Wi-Fi adapter instead of relying on the InterfaceDescription. This approach is more precise because the InterfaceIndex is a unique identifier for each network adapter. Additionally, I'll ensure the script properly handles spacing around the adapter name and avoids stripping or altering it.
Here’s how you can modify the script to use InterfaceIndex and print the adapter name with proper spacing:
Updated Script Using InterfaceIndex
# DNS-Manager.ps1
# Check for administrator privileges
if (-not ([Security.Principal.WindowsPrincipal] [Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator")) {
Write-Host "Please run this script as an administrator." -ForegroundColor Red
Read-Host "Press Enter to exit"
exit
}
# Get all active network adapters
Write-Host "Available network adapters:" -ForegroundColor Cyan
Get-NetAdapter | Where-Object { $_.Status -eq "Up" } | Select-Object InterfaceIndex, Name, InterfaceDescription | Format-Table -AutoSize
# Prompt user to enter the InterfaceIndex of the desired adapter
$interfaceIndex = Read-Host "Enter the InterfaceIndex of your Wi-Fi adapter"
# Retrieve the specific adapter by InterfaceIndex
$interface = Get-NetAdapter | Where-Object { $_.InterfaceIndex -eq $interfaceIndex }
if ($interface) {
# Print the adapter name with proper spacing
$adapterName = $interface.Name
Write-Host "`nThe selected adapter name is: ${adapterName}`n" -ForegroundColor Green
# Function to set custom DNS servers
function Set-CustomDNS {
Write-Host "Setting custom DNS servers for adapter: ${adapterName}"
Set-DnsClientDnsSettings -InterfaceIndex $interface.InterfaceIndex -ServerAddresses ("8.8.8.8", "8.8.4.4") -ResetConnectionSpecificSuffix -PassThru
Write-Host "DNS servers set successfully: Primary = 8.8.8.8, Alternative = 8.8.4.4" -ForegroundColor Green
}
# Function to reset DNS settings to Automatic (DHCP)
function Reset-DNS {
Write-Host "Resetting DNS settings to Automatic for adapter: ${adapterName}"
Set-DnsClientDnsSettings -InterfaceIndex $interface.InterfaceIndex -ResetConnectionSpecificSuffix -ResetServerAddresses -PassThru
Write-Host "DNS settings reverted to Automatic successfully." -ForegroundColor Green
}
# Main menu
Write-Host "DNS Manager Script" -ForegroundColor Cyan
Write-Host "1. Set Custom DNS (8.8.8.8, 8.8.4.4)"
Write-Host "2. Reset DNS to Automatic (DHCP)"
Write-Host "3. Exit"
# Prompt user for choice
$choice = Read-Host "Enter your choice (1/2/3)"
switch ($choice) {
1 { Set-CustomDNS }
2 { Reset-DNS }
3 { Write-Host "Exiting..." -ForegroundColor Yellow; exit }
default { Write-Host "Invalid choice. Exiting..." -ForegroundColor Red }
}
} else {
Write-Host "No adapter found with InterfaceIndex: $interfaceIndex" -ForegroundColor Red
Read-Host "Press Enter to exit"
}
User
I am worried that <YOUR_INTERFACE_INDEX> gets changed but I am sure the name doesnt get changed
Assistant
You're absolutely right to be concerned about the InterfaceIndex potentially changing, as it is dynamically assigned by the operating system and can vary between sessions or system reboots. On the other hand, the adapter name (e.g., Wi-Fi, Ethernet, etc.) is more stable and less likely to change unless you manually rename it.
To address your concern, we can modify the script to identify the adapter by its name instead of its InterfaceIndex. This ensures that the script remains reliable even if the InterfaceIndex changes.
Here’s how you can update the script to use the adapter name:
Updated Script Using Adapter Name
# DNS-Manager.ps1
# Check for administrator privileges
if (-not ([Security.Principal.WindowsPrincipal] [Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator")) {
Write-Host "Please run this script as an administrator." -ForegroundColor Red
Read-Host "Press Enter to exit"
exit
}
# Get all active network adapters
Write-Host "Available network adapters:" -ForegroundColor Cyan
Get-NetAdapter | Where-Object { $_.Status -eq "Up" } | Select-Object Name, InterfaceDescription | Format-Table -AutoSize
# Prompt user to enter the name of the desired adapter
$adapterName = Read-Host "Enter the name of your Wi-Fi adapter (e.g., Wi-Fi, Wi-Fi 66)"
# Retrieve the specific adapter by name
$interface = Get-NetAdapter | Where-Object { $_.Name -eq $adapterName }
if ($interface) {
# Print the adapter name with proper spacing
Write-Host "`nThe selected adapter name is: ${adapterName}`n" -ForegroundColor Green
# Function to set custom DNS servers
function Set-CustomDNS {
Write-Host "Setting custom DNS servers for adapter: ${adapterName}"
Set-DnsClientDnsSettings -InterfaceIndex $interface.InterfaceIndex -ServerAddresses ("8.8.8.8", "8.8.4.4") -ResetConnectionSpecificSuffix -PassThru
Write-Host "DNS servers set successfully: Primary = 8.8.8.8, Alternative = 8.8.4.4" -ForegroundColor Green
}
# Function to reset DNS settings to Automatic (DHCP)
function Reset-DNS {
Write-Host "Resetting DNS settings to Automatic for adapter: ${adapterName}"
Set-DnsClientDnsSettings -InterfaceIndex $interface.InterfaceIndex -ResetConnectionSpecificSuffix -ResetServerAddresses -PassThru
Write-Host "DNS settings reverted to Automatic successfully." -ForegroundColor Green
}
# Main menu
Write-Host "DNS Manager Script" -ForegroundColor Cyan
Write-Host "1. Set Custom DNS (8.8.8.8, 8.8.4.4)"
Write-Host "2. Reset DNS to Automatic (DHCP)"
Write-Host "3. Exit"
# Prompt user for choice
$choice = Read-Host "Enter your choice (1/2/3)"
switch ($choice) {
1 { Set-CustomDNS }
2 { Reset-DNS }
3 { Write-Host "Exiting..." -ForegroundColor Yellow; exit }
default { Write-Host "Invalid choice. Exiting..." -ForegroundColor Red }
}
} else {
Write-Host "No adapter found with the name: ${adapterName}" -ForegroundColor Red
Read-Host "Press Enter to exit"
}
User
# Check for admin rights
if (-NOT ([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator")) {
Write-Host "This script must be run as administrator." -ForegroundColor Red
Exit
}
# Find active WiFi adapter with "Wi-Fi 66" in the description
$adapterName = "Wi-Fi 66" # Replace with your actual adapter name
$interface = Get-NetAdapter | Where-Object { $_.Name -eq $adapterName }
#$interface = Get-NetAdapter | Where-Object {
# $_.Status -eq "Up" -and $_.InterfaceDescription -like "Wi-Fi 66"
#}
if (-not $interface) {
Write-Host "No active WiFi adapter with 'Wi-Fi 66' found." -ForegroundColor Red
Exit
}
# Define custom DNS servers
$customDns = @("g.g.g.g", "h.h.h.h")
# Get current DNS servers
$currentDns = Get-DnsClientServerAddress -InterfaceIndex $interface.InterfaceIndex | Select-Object -ExpandProperty ServerAddresses
# Check if current DNS matches the custom DNS
$allCustom = $true
foreach ($dns in $currentDns) {
if (-not ($customDns -contains $dns)) {
$allCustom = $false
break
}
}
if ($allCustom) {
# Revert to DHCP
Set-DnsClientServerAddress -InterfaceIndex $interface.InterfaceIndex -ResetToDefault
Write-Host "✅ Switched to automatic DNS (DHCP)." -ForegroundColor Green
} else {
# Set custom DNS
Set-DnsClientServerAddress -InterfaceIndex $interface.InterfaceIndex -ServerAddresses $customDns
Write-Host "✅ Switched to custom DNS: $customDns" -ForegroundColor Green
}
alright this way I found $adapterName = "Wi-Fi 66" # Replace with your actual adapter name $interface = Get-NetAdapter | Where-Object { $_.Name -eq $adapterName } interface but it gave
Set-DnsClientServerAddress : A parameter cannot be found that matches parameter name 'ResetToDefault'.
At D:\projects\commonUtils\shecanOnNOff\autoDnsRightside.ps1:37 char:74
+ ... rverAddress -InterfaceIndex $interface.InterfaceIndex -ResetToDefault
+ ~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidArgument: (:) [Set-DnsClientServerAddress], ParameterBindingException
+ FullyQualifiedErrorId : NamedParameterNotFound,Set-DnsClientServerAddress
Assistant
The error you're encountering occurs because the Set-DnsClientServerAddress cmdlet does not have a parameter named -ResetToDefault. This is likely due to a misunderstanding of the correct syntax for resetting DNS settings to automatic (DHCP).
To reset DNS settings to automatic, you need to use the -ResetServerAddresses parameter instead of -ResetToDefault. Let me explain and fix the issue.
Correct Syntax for Resetting DNS
The Set-DnsClientServerAddress cmdlet provides the following options:
Set Custom DNS Servers:
Use the -ServerAddresses parameter to specify custom DNS servers.
The -ResetToDefault parameter does not exist, which is why you're seeing the error:
Set-DnsClientServerAddress : A parameter cannot be found that matches parameter name 'ResetToDefault'.
Updated Script
Here’s the corrected version of your script:
# Check for admin rights
if (-NOT ([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator")) {
Write-Host "This script must be run as administrator." -ForegroundColor Red
Exit
}
# Find active WiFi adapter with "Wi-Fi 66" in the name
$adapterName = "Wi-Fi 66" # Replace with your actual adapter name
$interface = Get-NetAdapter | Where-Object { $_.Name -eq $adapterName }
if (-not $interface) {
Write-Host "No active WiFi adapter with '$adapterName' found." -ForegroundColor Red
Exit
}
# Define custom DNS servers
$customDns = @("g.g.g.g", "h.h.h.h")
# Get current DNS servers
$currentDns = Get-DnsClientServerAddress -InterfaceIndex $interface.InterfaceIndex | Select-Object -ExpandProperty ServerAddresses
# Check if current DNS matches the custom DNS
$allCustom = $true
foreach ($dns in $currentDns) {
if (-not ($customDns -contains $dns)) {
$allCustom = $false
break
}
}
if ($allCustom) {
# Revert to DHCP
Set-DnsClientServerAddress -InterfaceIndex $interface.InterfaceIndex -ResetServerAddresses
Write-Host "✅ Switched to automatic DNS (DHCP)." -ForegroundColor Green
} else {
# Set custom DNS
Set-DnsClientServerAddress -InterfaceIndex $interface.InterfaceIndex -ServerAddresses $customDns
Write-Host "✅ Switched to custom DNS: $customDns" -ForegroundColor Green
}
User
# Check for admin rights
if (-NOT ([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator")) {
Write-Host "This script must be run as administrator." -ForegroundColor Red
Exit
}
# Define your adapter name (ensure it matches exactly, including spaces)
$adapterName = "Wi-Fi 66" # Replace with your actual adapter name
$interface = Get-NetAdapter | Where-Object { $_.Name -eq $adapterName }
if (-not $interface) {
Write-Host "Adapter '$adapterName' not found." -ForegroundColor Red
Exit
}
# Get interface index
$interfaceIndex = $interface.InterfaceIndex
# Define custom DNS servers
$customDns = @("g.g.g.g", "h.h.h.h") # Replace with your preferred DNS
# Get current DNS servers
$currentDns = Get-DnsClientServerAddress -InterfaceIndex $interfaceIndex | Select-Object -ExpandProperty ServerAddresses
# Check if current DNS matches the custom DNS
$allCustom = $true
foreach ($dns in $currentDns) {
if (-not ($customDns -contains $dns)) {
$allCustom = $false
break
}
}
if ($allCustom) {
# Revert to DHCP using Set-NetIPInterface
Set-NetIPInterface -InterfaceIndex $interfaceIndex -Dhcp Enabled
Write-Host "✅ Switched to automatic DNS (DHCP)." -ForegroundColor Green
} else {
# Set custom DNS
Set-DnsClientServerAddress -InterfaceIndex $interfaceIndex -ServerAddresses $customDns
Write-Host "✅ Switched to custom DNS: $customDns" -ForegroundColor Green
}
this just changes to Switched to automatic DNS (DHCP). and doesn't take options to set other option
Assistant
The issue arises because the script is designed to automatically detect whether the current DNS matches the custom DNS ($customDns) and then switch between custom DNS and automatic (DHCP). However, it doesn't provide an interactive menu for you to explicitly choose between setting custom DNS or reverting to automatic.
If you want the script to allow you to choose between the two options manually, we need to add a menu-driven interface. This way, you can explicitly select whether to set custom DNS or reset to automatic (DHCP).
Here’s the updated script with an interactive menu:
Updated Script with Interactive Menu
# Check for admin rights
if (-NOT ([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator")) {
Write-Host "This script must be run as administrator." -ForegroundColor Red
Exit
}
# Define your adapter name (ensure it matches exactly, including spaces)
$adapterName = "Wi-Fi 66" # Replace with your actual adapter name
$interface = Get-NetAdapter | Where-Object { $_.Name -eq $adapterName }
if (-not $interface) {
Write-Host "Adapter '$adapterName' not found." -ForegroundColor Red
Exit
}
# Get interface index
$interfaceIndex = $interface.InterfaceIndex
# Define custom DNS servers
$customDns = @("g.g.g.g", "h.h.h.h") # Replace with your preferred DNS
# Function to set custom DNS
function Set-CustomDNS {
Set-DnsClientServerAddress -InterfaceIndex $interfaceIndex -ServerAddresses $customDns
Write-Host "✅ Switched to custom DNS: $customDns" -ForegroundColor Green
}
# Function to reset DNS to automatic (DHCP)
function Reset-DNS {
Set-DnsClientServerAddress -InterfaceIndex $interfaceIndex -ResetServerAddresses
Write-Host "✅ Switched to automatic DNS (DHCP)." -ForegroundColor Green
}
# Main menu
Write-Host "DNS Manager Script" -ForegroundColor Cyan
Write-Host "1. Set Custom DNS ($($customDns -join ', '))"
Write-Host "2. Reset DNS to Automatic (DHCP)"
Write-Host "3. Exit"
# Prompt user for choice
$choice = Read-Host "Enter your choice (1/2/3)"
switch ($choice) {
1 { Set-CustomDNS }
2 { Reset-DNS }
3 { Write-Host "Exiting..." -ForegroundColor Yellow; Exit }
default { Write-Host "Invalid choice. Exiting..." -ForegroundColor Red }
}
How It Works:
Admin Check:
Ensures the script is run with administrator privileges.
Find Adapter:
Identifies the Wi-Fi adapter by its name ($adapterName).
Define Custom DNS:
Specifies the custom DNS servers ().
User
it seems in between these tries things have got broken. I want sth to reset dns setting
Assistant
If you're experiencing issues with your DNS settings and want a simple, reliable way to reset your DNS settings to automatic (DHCP), we can create a minimal script that focuses solely on resetting the DNS configuration. This will ensure your system reverts to the default DNS settings provided by your DHCP server (e.g., your router).
Here’s a clean, straightforward PowerShell script to reset DNS settings for a specific network adapter:
Minimal Script to Reset DNS Settings
# Check for admin rights
if (-NOT ([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator")) {
Write-Host "This script must be run as administrator." -ForegroundColor Red
Exit
}
# Define your adapter name (ensure it matches exactly, including spaces)
$adapterName = "Wi-Fi 66" # Replace with your actual adapter name
$interface = Get-NetAdapter | Where-Object { $_.Name -eq $adapterName }
if (-not $interface) {
Write-Host "Adapter '$adapterName' not found." -ForegroundColor Red
Exit
}
# Get interface index
$interfaceIndex = $interface.InterfaceIndex
# Reset DNS to automatic (DHCP)
try {
Set-DnsClientServerAddress -InterfaceIndex $interfaceIndex -ResetServerAddresses
Write-Host "✅ DNS settings have been reset to automatic (DHCP)." -ForegroundColor Green
} catch {
Write-Host "❌ Failed to reset DNS settings. Error: $_" -ForegroundColor Red
}
How It Works:
Admin Check:
Ensures the script is run with administrator privileges.
Find Adapter:
Identifies the network adapter by its name ($adapterName).
Reset DNS to Automatic:
Uses Set-DnsClientServerAddress with the -ResetServerAddresses parameter to revert DNS settings to automatic (DHCP).
Error Handling:
Catches and displays any errors that occur during the process.
Steps to Use the Script:
Save the Script:
Copy the code into a text editor (e.g., Notepad).
Save the file with a .ps1 extension, e.g., Reset-DNS.ps1.
Run the Script:
Right-click on the .ps1 file and select "Run with PowerShell".
User
it seems in between these tries things have got broken. I want sth manual (including cmd and powershell commands) and not an script to reset dns setting
Assistant
If you want to manually reset your DNS settings without relying on a script, you can use either Command Prompt (CMD) or PowerShell commands. Below are step-by-step instructions for both methods:
Method 1: Using Command Prompt (CMD)
Steps:
Open Command Prompt as Administrator:
Press Win + S, type cmd, right-click on Command Prompt, and select "Run as administrator."
Identify Your Network Adapter:
Run the following command to list all network adapters and their names:
netsh interface show interface
Look for the name of your Wi-Fi adapter (e.g., Wi-Fi or Wi-Fi 66).
Reset DNS Settings to Automatic (DHCP):
Use the netsh command to reset the DNS settings for your adapter. Replace <AdapterName> with the exact name of your adapter (e.g., Wi-Fi 66):
netsh interface ip set dns name="<AdapterName>" source=dhcp
Example:
netsh interface ip set dns name="Wi-Fi 66" source=dhcp
Flush DNS Cache (Optional but Recommended):
To ensure no old DNS entries remain in the cache, run:
ipconfig /flushdns
Verify the Reset:
Test your internet connection by pinging a website:
ping google.com
Method 2: Using PowerShell
Steps:
Open PowerShell as Administrator:
Press Win + S, type PowerShell, right-click on Windows PowerShell, and select "Run as administrator."
Identify Your Network Adapter:
Run the following command to list all network adapters and their names:
Get-NetAdapter | Select-Object Name, Status
User
can u summarize my requests as a detailed prompt
Assistant
Certainly! Below is a detailed summary of your requests, formatted as a clear and structured prompt that captures all the key points you’ve raised throughout the conversation:
Detailed Prompt
Objective:
You want to reset DNS settings on your Windows 11 system due to issues that may have arisen from previous attempts to modify DNS configurations. You are looking for a manual solution (not a script) that uses either Command Prompt (CMD) or PowerShell commands to reset DNS settings to automatic (DHCP). Additionally, you want the solution to be straightforward and reliable, ensuring that your network adapter's DNS configuration is restored to its default state.
Key Requirements
Manual Reset of DNS Settings:
Provide step-by-step instructions to reset DNS settings manually using Command Prompt (CMD) or PowerShell.
Ensure the solution does not rely on scripts or automation.
Adapter-Specific Configuration:
The solution must target a specific network adapter by its name (e.g., Wi-Fi 66).
Include steps to identify the exact name of the active Wi-Fi adapter if it’s unclear.
Reset DNS to Automatic (DHCP):
The DNS settings should be reverted to automatic, allowing the DHCP server (e.g., your router) to assign DNS servers dynamically.
Optional: Clear DNS Cache:
Include instructions to flush the DNS cache to ensure no residual DNS entries interfere with the reset process.
Verification:
Provide a method to verify that the DNS reset was successful (e.g., testing internet connectivity).
Compatibility:
The solution should work on Windows 11 and be executable with administrator privileges.
Additional Context
Previous Attempts:
Earlier attempts to modify DNS settings using scripts may have caused instability or misconfiguration. As a result, you prefer a manual approach to ensure full control over the process.
Option 2: Resets DNS settings to "Automatic" (DHCP).
Option 3: Exits the script.
Dynamic Interface Detection:
The script dynamically identifies the currently active Wi-Fi interface using Get-NetAdapter.
Administrative Privileges:
The script checks if it is running with administrator privileges and exits if not.
User Interaction:
The script displays a menu and prompts the user to select an option.
Steps to Use the Combined Script:
Create the Script:
Open Notepad or any text editor.
Copy and paste the above script into a file.
Save the file with a .ps1 extension, e.g., DNS-Manager.ps1.
Run the Script:
Right-click on the .ps1 file and select "Run with PowerShell".
If prompted by User Account Control (UAC), click "Yes" to grant administrator privileges.
Choose an Option:
Follow the on-screen menu to select either 1 (Set Custom DNS) or 2 (Reset DNS to Automatic).
Optional: Create a Batch File:
To make it easier to execute the script, you can create a batch file (DNS-Manager.bat) that calls the PowerShell script.
Example:
@echo off
PowerShell -ExecutionPolicy Bypass -File "C:\Path\To\DNS-Manager.ps1"
pause
Place the Script in a Secure Location:
Store the script and batch file in a directory where they can be easily accessed, such as C:\Scripts.
Notes:
Custom DNS Servers: Modify the IP addresses (8.8.8.8 and 8.8.4.4) in the Set-CustomDNS function if you want to use different DNS servers.
Error Handling: The script includes basic error handling to notify you if no active Wi-Fi interface is found.
Execution Policy: The -ExecutionPolicy Bypass flag in the batch file temporarily allows the script to run, bypassing the default execution policy restrictions.
Final Answer:
The combined script DNS-Manager.ps1 provides a menu-driven interface to either set custom DNS servers or reset DNS settings to automatic. You can execute it directly or via a batch file for convenience.
Get-NetAdapter
Menu Options:
Option 1: Sets custom DNS servers (8.8.8.8 as primary and 8.8.4.4 as alternative).
Option 2: Resets DNS settings to "Automatic" (DHCP).
Option 3: Exits the script.
User Interaction:
The script displays a menu and prompts the user to select an option.
Error Handling:
If no active Wi-Fi interface is found, the script notifies the user and exits gracefully.
Steps to Use the Script:
Save the Script:
Copy the above code into a text editor (e.g., Notepad).
Save the file with a .ps1 extension, e.g., DNS-Manager.ps1.
Run the Script:
Right-click on the .ps1 file and select "Run with PowerShell".
If prompted by User Account Control (UAC), click "Yes" to grant administrator privileges.
Choose an Option:
Follow the on-screen menu to select either 1 (Set Custom DNS) or 2 (Reset DNS to Automatic).
Optional: Create a Batch File:
To make it easier to execute the script, create a batch file (DNS-Manager.bat) with the following content:
@echo off
PowerShell -ExecutionPolicy Bypass -File "C:\Path\To\DNS-Manager.ps1"
pause
Replace C:\Path\To\DNS-Manager.ps1 with the actual path to the script.
Place the Script in a Secure Location:
Store the script and batch file in a directory where they can be easily accessed, such as C:\Scripts.
Notes:
Custom DNS Servers: Modify the IP addresses (8.8.8.8 and 8.8.4.4) in the Set-CustomDNS function if you want to use different DNS servers.
Execution Policy: The -ExecutionPolicy Bypass flag in the batch file temporarily allows the script to run, bypassing the default execution policy restrictions.
Compatibility: This script works on Windows 10 and Windows 11.
Final Answer:
The provided PowerShell script (DNS-Manager.ps1) combines both functionalities (setting custom DNS and resetting to automatic) into a single file with a menu-driven interface. You can execute it directly or via a batch file for convenience.
Reset to Automatic
When you choose option 2, the script resets the DNS settings to "Automatic" (DHCP) for the active Wi-Fi interface.
Example Execution Flow:
Connect to Any Wi-Fi Network:
For example, connect to your home Wi-Fi (MyHomeWiFi) or a public Wi-Fi network (PublicHotspot).
Run the Script:
Execute the script (DNS-Manager.ps1) with administrator privileges.
Choose an Option:
Select 1 to set custom DNS servers or 2 to reset DNS settings to automatic.
Script Automatically Detects the Wi-Fi Interface:
The script identifies the active Wi-Fi interface (e.g., Wi-Fi) and applies the DNS changes to it.
What If You Have Multiple Network Adapters?
If you have multiple network adapters (e.g., Ethernet and Wi-Fi), the script ensures it only targets the active Wi-Fi interface. It does this by filtering for:
Status -eq "Up": Only active adapters.
InterfaceDescription -like "*Wi-Fi*": Only Wi-Fi adapters.
Final Answer:
You do not need to set or hardcode the Wi-Fi name (SSID) in the script. The script dynamically detects the currently active Wi-Fi interface based on its status and description. This makes the script flexible and compatible with any Wi-Fi network you’re connected to. Simply ensure you’re connected to a Wi-Fi network before running the script, and it will automatically apply the DNS changes to the correct interface.
Now, when you run the script, it will wait for you to press Enter before closing.
Solution 3: Use a Batch File to Run the Script
You can create a batch file that calls the PowerShell script and keeps the window open after execution.
Steps:
Create a Batch File:
Open Notepad and paste the following code:
@echo off
PowerShell -ExecutionPolicy Bypass -File "C:\Path\To\DNS-Manager.ps1"
pause
Replace C:\Path\To\DNS-Manager.ps1 with the actual path to your script.
Save the Batch File:
Save the file with a .bat extension, e.g., Run-DNS-Manager.bat.
Run the Batch File:
Double-click the .bat file to run the script.
After the script finishes, the pause command will keep the window open until you press a key.
Solution 4: Run the Script in the Integrated Script Environment (ISE)
If you prefer a graphical interface, you can use the PowerShell ISE to run the script.
Steps:
Open PowerShell ISE:
Press Win + S, type PowerShell ISE, and open it.
Load the Script:
In PowerShell ISE, click File > Open and select your DNS-Manager.ps1 script.
Run the Script:
Press F5 or click the green "Run" button to execute the script.
Interact with the Menu:
The script will run in the ISE console, and the window will remain open for you to interact with.
Final Answer
To prevent the PowerShell window from closing immediately:
Run the script from an existing PowerShell window (preferred).
Modify the script to include a pause (Read-Host "Press Enter to exit").
Use a batch file with the pause command.
Run the script in PowerShell ISE for a more interactive experience.
Choose the solution that works best for your workflow!
In this case, the InterfaceDescription is Intel(R) Wi-Fi 6 AX201.
When to Modify the Script
If your adapter description does not contain "Wi-Fi" (e.g., it’s named something like Wireless Network Connection), you can update the script to match your adapter. For example:
You do not need to replace *Wi-Fi* with *Wi-Fi 66* unless your adapter description is completely different and does not contain "Wi-Fi." The *Wi-Fi* wildcard will already match descriptions like Wi-Fi 66 or Intel(R) Wi-Fi 6 AX201.
If you’re unsure, use the Get-NetAdapter command to check your adapter's InterfaceDescription and adjust the filter only if necessary.
This will print all detected adapters to the console, helping you identify why your Wi-Fi adapter isn’t being detected.
Final Answer
The error No active Wi-Fi adapter found occurs because the script cannot detect an active Wi-Fi adapter. To resolve this:
Verify the Wi-Fi adapter is active and connected using Get-NetAdapter.
Ensure Wi-Fi is enabled in Windows settings.
Update the script’s filter to match your adapter’s InterfaceDescription.
Check for driver issues and update or reinstall the Wi-Fi adapter driver if necessary.
By following these steps, you should be able to resolve the issue and get the script working correctly.
How It Works:
List Available Adapters:
The script lists all active network adapters (Status -eq "Up") along with their InterfaceIndex, Name, and InterfaceDescription.
Prompt for InterfaceIndex:
The user is prompted to enter the InterfaceIndex of the desired Wi-Fi adapter.
Retrieve Adapter by InterfaceIndex:
The script retrieves the adapter using the provided InterfaceIndex.
Print Adapter Name:
The adapter name is printed with proper spacing using ${adapterName} to avoid any issues with spaces or special characters.
Set or Reset DNS:
The script applies the DNS changes to the selected adapter based on the user's choice.
Example Execution Flow:
Run the script as Administrator.
The script displays available adapters:
Available network adapters:
InterfaceIndex Name InterfaceDescription
-------------- ---- --------------------
1 Ethernet Realtek PCIe GbE Family Controller
7 Wi-Fi Intel(R) Wi-Fi 6 AX201
Enter the InterfaceIndex of your Wi-Fi adapter (e.g., 7).
The script confirms the selected adapter:
The selected adapter name is: Wi-Fi
Choose an option from the menu:
Option 1: Set custom DNS servers (8.8.8.8, 8.8.4.4).
Option 2: Reset DNS settings to automatic (DHCP).
Option 3: Exit.
Key Points:
Adapter Name Spacing:
The script uses ${adapterName} to ensure proper handling of spaces in the adapter name. For example, if the adapter name is Wi-Fi 66, it will be displayed correctly without stripping spaces.
Unique Identification:
Using InterfaceIndex ensures that the correct adapter is selected, even if multiple adapters have similar names or descriptions.
Error Handling:
If no adapter is found with the provided InterfaceIndex, the script notifies the user and exits gracefully.
Final Answer:
You can use the updated script above to select your Wi-Fi adapter by its InterfaceIndex. The script ensures proper spacing around the adapter name using ${adapterName} and avoids stripping spaces. This approach provides precise control over which adapter is modified and avoids ambiguity.
How It Works:
List Available Adapters:
The script lists all active network adapters (Status -eq "Up") along with their Name and InterfaceDescription.
Prompt for Adapter Name:
The user is prompted to enter the exact name of the desired adapter (e.g., Wi-Fi, Wi-Fi 66).
Retrieve Adapter by Name:
The script retrieves the adapter using the provided name ($_.Name -eq $adapterName).
Set or Reset DNS:
Once the adapter is identified, the script applies the DNS changes based on the user's choice.
Error Handling:
If no adapter is found with the provided name, the script notifies the user and exits gracefully.
Why Use the Adapter Name?
Stability: The adapter name (e.g., Wi-Fi, Ethernet) is less likely to change compared to the InterfaceIndex.
Ease of Use: You don’t need to look up the InterfaceIndex every time you run the script.
Reliability: Even if the InterfaceIndex changes due to system updates or reboots, the adapter name remains consistent.
Example Execution Flow:
Run the script as Administrator.
The script displays available adapters:
Available network adapters:
Name InterfaceDescription
---- --------------------
Ethernet Realtek PCIe GbE Family Controller
Wi-Fi Intel(R) Wi-Fi 6 AX201
Enter the name of your Wi-Fi adapter (e.g., Wi-Fi).
The script confirms the selected adapter:
The selected adapter name is: Wi-Fi
Choose an option from the menu:
Option 1: Set custom DNS servers (8.8.8.8, 8.8.4.4).
Option 2: Reset DNS settings to automatic (DHCP).
Option 3: Exit.
Key Points:
Adapter Name Stability:
The adapter name is unlikely to change unless you manually rename it in the system settings.
Proper Spacing:
The script uses ${adapterName} to ensure proper handling of spaces in the adapter name.
Dynamic Detection:
The script dynamically detects the adapter based on its name, ensuring compatibility across different systems.
Final Answer:
The updated script identifies the adapter by its name (e.g., Wi-Fi, Wi-Fi 66) instead of its InterfaceIndex. This approach ensures reliability, as the adapter name is stable and less likely to change. You can now confidently use the script without worrying about the InterfaceIndex changing.
Key Changes
Replaced -ResetToDefault with -ResetServerAddresses:
The correct parameter for resetting DNS to automatic is -ResetServerAddresses.
Improved Error Handling:
If no adapter is found with the specified name ($adapterName), the script exits gracefully with an error message.
Dynamic DNS Matching:
The script checks whether the current DNS settings match the custom DNS servers ($customDns) and switches accordingly:
If the current DNS matches the custom DNS, it resets to automatic (DHCP).
Otherwise, it sets the custom DNS servers.
How It Works
Admin Check:
Ensures the script is run with administrator privileges.
Find Adapter:
Identifies the Wi-Fi adapter by its name ($adapterName).
Get Current DNS Settings:
Retrieves the current DNS server addresses for the selected adapter.
Switch DNS:
If the current DNS matches the custom DNS ($customDns), it resets to automatic (DHCP).
Otherwise, it sets the custom DNS servers.
Example Execution Flow
Run the script as Administrator.
The script identifies the adapter with the name Wi-Fi 66.
If the current DNS matches g.g.g.g and h.h.h.h, it resets to automatic (DHCP):
✅ Switched to automatic DNS (DHCP).
Otherwise, it sets the custom DNS servers:
✅ Switched to custom DNS: g.g.g.g h.h.h.h
Final Answer
The error occurred because the -ResetToDefault parameter does not exist in the Set-DnsClientServerAddress cmdlet. The correct parameter to reset DNS to automatic is -ResetServerAddresses. The updated script resolves this issue and ensures the DNS settings are switched correctly between custom DNS and automatic (DHCP).
$customDns
Interactive Menu:
Displays a menu with three options:
1: Set custom DNS.
2: Reset DNS to automatic (DHCP).
3: Exit the script.
Execute Based on User Choice:
If the user selects 1, the script sets the custom DNS servers.
If the user selects 2, the script resets DNS to automatic (DHCP).
If the user selects 3, the script exits.
Error Handling:
If the user enters an invalid choice, the script notifies them and exits gracefully.
Example Execution Flow:
Run the script as Administrator.
The script displays the menu:
DNS Manager Script
1. Set Custom DNS (g.g.g.g, h.h.h.h)
2. Reset DNS to Automatic (DHCP)
3. Exit
Enter your choice:
If you enter 1, the script sets the custom DNS:
✅ Switched to custom DNS: g.g.g.g, h.h.h.h
If you enter 2, the script resets DNS to automatic:
✅ Switched to automatic DNS (DHCP).
If you enter 3, the script exits:
Exiting...
Key Points:
Interactive Menu:
The script now allows you to explicitly choose between setting custom DNS or resetting to automatic.
Custom DNS Definition:
You can easily modify the $customDns array to use different DNS servers.
Error Handling:
The script gracefully handles invalid choices and missing adapters.
Final Answer:
The updated script includes an interactive menu that allows you to explicitly choose between setting custom DNS or resetting to automatic (DHCP). This resolves the issue where the script only performed one action automatically without giving you options.
If prompted by User Account Control (UAC), click Yes to grant administrator privileges.
Verify the Reset:
After running the script, your DNS settings will be reset to automatic (DHCP).
Additional Notes:
Adapter Name:
Ensure the $adapterName variable matches the exact name of your network adapter (e.g., Wi-Fi 66). You can confirm the adapter name by running:
Get-NetAdapter | Select-Object Name, Status
What Happens When DNS Is Reset?:
Resetting DNS to automatic means your system will use the DNS servers provided by your DHCP server (usually your router). This ensures you don’t have hardcoded DNS settings interfering with your network connectivity.
Testing Connectivity:
After resetting DNS, test your internet connection to ensure everything works correctly. For example:
Test-NetConnection google.com
Final Answer:
The provided script resets DNS settings to automatic (DHCP) for a specific network adapter. It is simple, reliable, and ensures your DNS configuration is restored to the default state. Replace the $adapterName variable with the exact name of your adapter, and run the script as an administrator.
Look for the name of your Wi-Fi adapter (e.g., Wi-Fi or Wi-Fi 66).
Reset DNS Settings to Automatic (DHCP):
Use the Set-DnsClientServerAddress cmdlet to reset DNS settings for your adapter. Replace <AdapterName> with the exact name of your adapter:
Both methods will reset your DNS settings to automatic (DHCP). Choose the one you're more comfortable with!
Preferred Tools:
You are open to using either Command Prompt (CMD) or PowerShell, but the solution must be simple and easy to follow.
Network Adapter Name:
Your Wi-Fi adapter is named Wi-Fi 66, but you want instructions that allow you to confirm the adapter name dynamically in case it changes or is unclear.
Expected Output
A clear, step-by-step guide for resetting DNS settings manually using:
Command Prompt (CMD):
Commands to identify the adapter.
Commands to reset DNS to automatic.
Optional steps to flush the DNS cache.
Verification steps.
PowerShell:
Commands to identify the adapter.
Commands to reset DNS to automatic.
Optional steps to flush the DNS cache.
Verification steps.
Final Notes
The solution should be designed for users who prefer a hands-on, manual approach to troubleshooting DNS issues. It should avoid reliance on scripts or automation while ensuring compatibility with Windows 11 and providing robust error handling (e.g., confirming the adapter exists before proceeding).
This detailed prompt captures all your requirements and provides a clear structure for addressing your needs. Let me know if you’d like further refinements!