Sheraram_Prajapat
Sheraram_Prajapat

Reputation: 597

Powershell script Changing DNS properties working on 32 bit system but not working on 64 bit

This is the script that changes the configuration of DNS properties like setting the IP address, Default Gateway, and DNS server address which can be found at Control Panel -> Network and sharing center -> select adapter -> Properties -> Internet Protocol Version 4(TCP/IPv4).enter image description here

This script is running perfectly on windows 7 32-bit and windows 10 32-bit systems but for some reason, it's not working on windows 7 64 bit. Whenever I try to change the IP address it throws the error code 97 i.e. Interface not configurable. If I use the function on the adapter directly in PowerShell command line like $adapter = (get-wmiobject win32_networkadapterconfiguration | where-object {$_.index -eq 7}) $adapter.EnableStatic("192.168.1.50", "255.255.255.0") it's working on the Powershell command-line user interface. I can't figure out why or how is it happening?

UPDATE:

I tried to debug the code and I found that for some reason I can't fetch AdapterIndex from hash_Table network_info like

$network_info = Get-IPAdapterInformation 
[string]$AdapterName = $network_info.AdapterName
[string]$AdapterInterfaceIndex = $network_info.AdapterInterfaceIndex
[string]$AdapterIndex = $network_info.AdapterIndex
cls
#function to get Adapter Info based on Mac-Address
function Get-IPAdapterInformation{
#    [CmdletBinding()]
    $AdapterInfo = @{}
#    $MyMacAddress = "00:15:5D:00:A3:07"
    $MyMacAddress = Read-Host "Enter Mac Address of Adapter"
    $MyMacAddress = $MyMacAddress.Trim()
    Try { $IPconfigset = Get-WmiObject Win32_NetworkAdapterConfiguration -Namespace "root\CIMv2" -ErrorAction:Stop  | ? {$_.IPEnabled -and ($_.MACAddress -ne $null)} } Catch { return $IPs }
    foreach ($ip in $IPconfigset) {
        if($ip.MACAddress -eq $MyMacAddress){
            $i = New-Object PSObject | Select-Object Index, InterfaceIndex, IPAddress, Subnet, Name, DeviceName, MACAddress, DNSSearchOrder, Gateway, Status
            $i.Index = $ip.Index
            $i.InterfaceIndex = $ip.InterfaceIndex
            $i.IPAddress = $ip.IPAddress[0]
            $i.Subnet = $ip.IPSubnet[0]
            $i.DeviceName = $ip.Description
            $i.MACAddress = $ip.MACAddress
            $i.DNSSearchOrder = $ip.DNSServerSearchOrder
            $i.Gateway = $ip.DefaultIPGateway
            $i.Name = (Get-WmiObject win32_networkadapter -ErrorAction:SilentlyContinue | ? {$_.Name -eq $i.DeviceName}).netconnectionid
            $i.Status = (Get-WmiObject win32_networkadapter -ErrorAction:SilentlyContinue | ? {$_.Name -eq $i.DeviceName}).NetConnectionStatus
            $AdapterInfo.add('AdapterName', $i.Name)
            $AdapterInfo.add('AdapterInterfaceDescription', $i.DeviceName)
            $AdapterInfo.add('AdapterInterfaceIndex', $i.InterfaceIndex)
            $AdapterInfo.add('AdapterIndex', $i.Index)
        }
      }
    if($AdapterInfo -ne $null){
        Write-Host "Adapter Found!" -ForegroundColor Green
        Write-Host "Adapter Name:"$AdapterInfo.AdapterName -ForegroundColor Green
        Write-Host "Adapter InterfaceIndex:"$AdapterInfo.AdapterInterfaceIndex -ForegroundColor Green
        Write-Host "Adapter Interface Description:"$AdapterInfo.AdapterInterfaceDescription -ForegroundColor Green
        Write-Host "Adapter Index:"$AdapterInfo.AdapterIndex -ForegroundColor Green        
    }else{
        Write-Host "No Adapter found with given MacAddress" -ForegroundColor Ref
    }
    return $AdapterInfo
}


#====================================================================
# STEP #2: SETUP NETWORK
#====================================================================
Write-Host "Available Network Adapters on this Device:" -ForegroundColor Green
Get-WmiObject Win32_networkAdapter | ?{$_.MACAddress -ne $null} | Select NetConnectionID, Name, MACAddress, Description, InterfaceIndex, NetConnectionStatus

$network_info = Get-IPAdapterInformation
#$network_info
[string]$AdapterName = $network_info.AdapterName
[string]$AdapterInterfaceIndex = $network_info.AdapterInterfaceIndex
[string]$AdapterIndex = $network_info.AdapterIndex


#Returns StatusCode Description based on given status code
function Get-StatusCodeDescripton($StatusCode){
    Switch($StatusCode){
        0{
            return "Successful completion, no reboot required"
        }1{
            return "Successful completion, reboot required"
        }64{         
            return "Method not supported on this platform"
        }65{
            return "Unknown failure"
        }66{
            return "Invalid subnet mask"
        }67{
            return "An error occurred while processing an Instance that was returned"
        }68{
            return "Invalid input parameter"
        }69{
            return "More than 5 gateways specified"
        }70{
            return "Invalid IP address"
        }71{
            return "Invalid gateway IP address"
        }72{
            return "An error occurred while accessing the Registry for the requested information"
        }73{
            return "Invalid domain name"
        }74{
            return "Invalid host name"
        }75{
            return "No primary/secondary WINS server defined"
        }76{
            return "Invalid file"
        }77{
            return "Invalid system path"
        }78{
            return "File copy failed"
        }79{
            return "Invalid security parameter"
        }80{
            return "Unable to configure TCP/IP service"
        }81{
            return "Unable to configure DHCP service"
        }82{
            return "Unable to renew DHCP lease"
        }83{
            return "Unable to release DHCP lease"
        }84{
            return "IP not enabled on adapter"
        }85{
            return "IPX not enabled on adapter"
        }86{
            return "Frame/network number bounds error"
        }87{
            return "Invalid frame type"
        }88{
            return "Invalid network number"
        }89{
            return "Duplicate network number"
        }90{
            return "Parameter out of bounds"
        }91{
            return "Access denied"
        }92{
            return "Out of memory"
        }93{
            return "Already exists"
        }94{
            return "Path, file or object not found"
        }95{
            return "Unable to notify service"
        }96{
            return "Unable to notify DNS service"
        }97{
            return "Interface not configurable"
        }98{
            return "Not all DHCP leases could be released/renewed"
        }100{
            return "DHCP not enabled on adapter"
        }101{
            return "Some error occured!"       
        }default{
            return "Some Unknown error occurred!"
        }
    }
}

#Set IP address(Input: IPAddrss, DefaultGateway, SubnetMask(Optional))
function Set-IPAddress{
    [CmdletBinding()]
    Param(
        #IP Address
        [Parameter(Mandatory=$true,
            ValueFromPipelineByPropertyName=$true,
            Position=0)]
        [String]$IPAddress,
        #Default Gateway
        [Parameter(Mandatory=$true, 
            ValueFromPipelineByPropertyName=$true,
            Position=1)]
        [String]$DefaultGateway
    )
    $IPAddress
    $SubNetMask = Read-Host "Enter Subnet Mask[Default 255.255.255.0]"
    if(-not $SubNetMask){
        $SubNetMask ="255.255.255.0"
    }
    $SubNetMask
    $adapter = (get-wmiobject win32_networkadapterconfiguration -ErrorAction:SilentlyContinue | where-object {$_.index -eq $AdapterIndex})
    $IPandSubnetMaskResult = $adapter.EnableStatic($IPAddress, $SubNetMask) #IPAddress, Subnet Mask    
    $IPandSubnetMaskResultCode = $IPandSubnetMaskResult.ReturnValue
    $IPandSubnetMaskResultCode
    $IPandSubnetMaskResultDesciption = Get-StatusCodeDescripton($IPandSubnetMaskResultCode)
    if(($IPandSubnetMaskResultCode -eq 0) -or ($IPandSubnetMaskResultCode -eq 1)){
        Write-Host $IPandSubnetMaskResultDesciption -ForegroundColor Green
        Write-Host "[SUCCESS] Changed Static IP Address to: $($IPAddress)." -ForegroundColor Green         
    }else{
        Write-Host $IPandSubnetMaskResultDesciption -ForegroundColor Red
    }
    $GatewayResult = $adapter.SetGateways($DefaultGateway)
    $GatewayResultCode = $GatewayResult.ReturnValue
    $GatewayResultDescription =  Get-StatusCodeDescripton($GatewayResultCode)
    if(($GatewayResultCode -eq 0) -or ($GatewayResultCode -eq 1)){
        Write-Host $GatewayResultDescription -ForegroundColor Green
        Write-Host "[SUCCESS] Changed Default GAteway to: $($DefaultGateway)." -ForegroundColor Green    
    }else{
        Write-Host $GatewayResultDescription -ForegroundColor Red
        Write-Host "An Error occurred!" -ForegroundColor Red
    }
    Sleep -Seconds 4 #sometimes setting instantly IP address gives error 67.
}

#Set DNS Server Address(Input:PrimaryDNSAddress, SecondaryDNSAddress(Optional))
function Set-DNSServerAdddress{
    [CmdletBinding()]
    Param(
        #Primary DNS Server Address
        [Parameter(Mandatory=$true,
            ValueFromPipelineByPropertyName=$true,
            Position=0)]
        [String]$PrimaryDNSAddress
    )
    $SecondaryDNSAddress = Read-Host "Enter Secondary DNS Address[Optional]"
    $adapter = (get-wmiobject win32_networkadapterconfiguration -ErrorAction:SilentlyContinue | where-object {$_.index -eq $AdapterIndex})
    if($SecondaryDNSAddress){
        $SetDNSServerAddressResult = $adapter.SetDNSServerSearchOrder(@($PrimaryDNSAddress, $SecondaryDNSAddress))
    }else{
        $SetDNSServerAddressResult = $adapter.SetDNSServerSearchOrder(@($PrimaryDNSAddress))
    }
    $SetDNSServerAddressResultCode = $SetDNSServerAddressResult.ReturnValue
    $SetDNSServerAddressResultDescription =  Get-StatusCodeDescripton($SetDNSServerAddressResult)
    if(($SetDNSServerAddressResultCode -eq 0) -or ($SetDNSServerAddressResultCode -eq 1)){
        Write-Host $SetDNSServerAddressResultDescription -ForegroundColor Green
        Write-Host "[SUCCESS] Set DNS Servers to: $($PrimaryDNSAddress), $($SecondaryDNSAddress)." -ForegroundColor Green    
    }else{
        Write-Host $GatewayResultDescription -ForegroundColor Red
        Write-Host "An Error occurred!" -ForegroundColor Red
    }    
    Sleep -Seconds 4
}


function Set-DNSSererAddressAutomatically{
    $userInput = Read-Host "Do you want to set DNS Server Address Automatically? [y]Yes  [n]No[Default NO]"
    if($userInput -eq "y" -or $userInput -eq "yes"){       
        $adapter = (get-wmiobject win32_networkadapterconfiguration -ErrorAction:SilentlyContinue | where-object {$_.index -eq $AdapterIndex})
        $SetDNSServerAddressAutomaticallyResult = $adapter.SetDNSServerSearchOrder()
        $SetDNSServerAddressAutomaticallyResultCode = $SetDNSServerAddressAutomaticallyResult.ReturnValue
        $SetDNSServerAddressAutomaticallyResultDescription =  Get-StatusCodeDescripton($SetDNSServerAddressAutomaticallyResultCode)
        if(($SetDNSServerAddressAutomaticallyResultCode -eq 0) -or ($SetDNSServerAddressAutomaticallyResultCode -eq 1)){
            Write-Host $SetDNSServerAddressAutomaticallyResultDescription -ForegroundColor Green
            Write-Host "[SUCCESS] Set DNS Servers Automatically." -ForegroundColor Green    
        }else{
            Write-Host $SetDNSServerAddressAutomaticallyResultDescription -ForegroundColor Red
            Write-Host "An Error occurred!" -ForegroundColor Red
        }    
    }else{
        Write-Warning "You selected NO"
    }
    Sleep -Seconds 4
}

function Set-IPAddressAutomatically{
    $userInput = Read-Host "Set IP Automatically? [y]Yes  [n]No[Default NO]"
    if($userInput -eq "y" -or $userInput -eq "yes"){       
        $adapter = (get-wmiobject win32_networkadapterconfiguration -ErrorAction:SilentlyContinue | where-object {$_.index -eq $AdapterIndex})
        $SetIPAddressAutomaticallyResult = $adapter.EnableDHCP()
        $SetIPAddressAutomaticallyResultCode = $SetIPAddressAutomaticallyResult.ReturnValue
        $SetIPAddressAutomaticallyResultDescription =  Get-StatusCodeDescripton($SetIPAddressAutomaticallyResultCode)
        if(($SetIPAddressAutomaticallyResultCode -eq 0) -or ($SetIPAddressAutomaticallyResultCode -eq 1)){
            Write-Host $SetIPAddressAutomaticallyResultDescription -ForegroundColor Green
            Write-Host "[SUCCESS] Set IP Addresss Automatically." -ForegroundColor Green    
        }else{
            Write-Host $SetIPAddressAutomaticallyResultDescription -ForegroundColor Red
            Write-Host "An Error occurred!" -ForegroundColor Red
        }    
    }else{
        Write-Warning "You selected NO"
    }
    Sleep -Seconds 4
}
#Set-IPAddress #working
#Set-DNSServerAdddress #not working with2nd DNS Server Address
#Set-DNSSererAddressAutomatically # working
#Set-IPAddressAutomatically #working


$choices = "Select Operation:
    0. Print Choices
    1. Set IP Address and Default Gateway
    2. Set DNS Server Address
    3. Set IP Address Automatically
    4. Set DNS Server Address Automatically
    t. exit/terminate
"
$status = $true
while($status){
    $choice = Read-Host "Select choice: $choices"
    $choice
    switch($choice){
        0{
            Write-Host " ==> Print choices: $choices" -ForeGround Green
            break
        }
        1{
            Write-Host " ==> Set IP Address and Default Gateway" -ForeGround Green
            Set-IPAddress
            break
        }
        2{
            Write-Host " ==> Set DNS Server Address" -ForeGround Green
            Set-DNSServerAdddress
            break
        }
        3{
            Write-Host " ==> Set IP Address Automatically" -ForeGround Green
            Set-IPAddressAutomatically
            break
        }
        
        4{
            Write-Host " ==> Set DNS Server Address Automatically"
            Set-DNSSererAddressAutomatically
            break
        }            
        t{
            Write-Host " ==> Exit" -ForeGround Green
            
            $status = $false
        }                    
        }
}

#Index          : 7
#InterfaceIndex : 11
#IPAddress      : 192.168.234.197
#Subnet         : 255.255.240.0
#Name           : Local Area Connection
#DeviceName     : Microsoft Virtual Machine Bus Network Adapter
#MACAddress     : 00:15:5D:00:A3:07
#DNSSearchOrder : {192.168.224.1}
#Gateway        : {192.168.224.1}
#Status         : 2


Upvotes: 1

Views: 766

Answers (1)

Cpt.Whale
Cpt.Whale

Reputation: 5341

I did go ahead and run the entire script as-is up to where you were having trouble at $network_info.AdapterIndex on a machine running Windows 7 64-bit, and I'm able to pull the $AdapterIndex without issues, so it may just be that VM?

I would also recommend feeding $AdapterIndex as a parameter to your other functions instead of basically using it as a global variable.

For the issue of not being able to access an element of a hashtable, I believe the problem is probably earlier in your script. For example, you're not really checking if $network_info has any data. My guess would be something like your WMI query on that VM doesn't actually return a valid object. Try out something like this on the 64-bit win7 VM - basically just removing some of the function structures and -erroraction SilentlyContinue flags:

$MyMacAddress = "00:00:00:3C:7A:00" # yours here
$MatchingAdapter = Get-WmiObject Win32_NetworkAdapterConfiguration | 
  Where {$_.IPEnabled -and ($_.MACAddress -eq $MyMacAddress )}

# double-check you actually found an adapter via MAC
if (!$MatchingAdapter) {throw "No adapter found with MAC address $MyMacAddress";break}

$AdapterInfo = @{
  AdapterName = (
      Get-WmiObject -Query "SELECT netconnectionID FROM win32_networkadapter WHERE Name = '$($MatchingAdapter.Description)'"
    ).netconnectionid
  AdapterInterfaceDescription = $MatchingAdapter.Description
  AdapterInterfaceIndex = $MatchingAdapter.InterfaceIndex
  AdapterIndex = $MatchingAdapter.Index
}

[PSCustomObject]$AdapterInfo | fl

If that returns reasonable values, then this should work too:

$Adapter = Get-WMIObject -Query "SELECT * FROM win32_networkadapterconfiguration WHERE index = '$($MatchingAdapter.Index)'"
$IPandSubnetMaskResult = $adapter.EnableStatic($IPAddress, $SubNetMask)

Upvotes: 1

Related Questions