Configure gateway metric (Perl)

This code can be found in Chapter 1 of Windows Server 2003 Networking Recipes

Purchase XP Cookbook or Networking Recipes for only $25 plus shipping! While supplies last.

Find out how to download all of the Perl code from this site.

# From the book "Windows Server 2003 Networking Recipes"

# This code configured the local interface
#   with default gateway of 10.0.0.1,
#   and a metric of 1
# ------ SCRIPT CONFIGURATION ------

use Win32::OLE qw(in);

$strComputer = '.';
$strGateway = ['10.0.0.1'];
$strGatewayMetric = [1];
# --------- END CONFIGURATION ------

$objWMIService = Win32::OLE->GetObject('winmgmts:' . '{impersonationLevel=impersonate}!\\\\' . $strComputer . '\\root\\cimv2');

$adapters = $objWMIService->ExecQuery('Select * from Win32_NetworkAdapterConfiguration where IPEnabled=TRUE');

foreach my $a (in $adapters) {
    $errGateways = $a->SetGateways($strGateway, $strGatewayMetric);
    if ($errGateways == 0) {
        print "Success! The default gateway has been set.\n";
    }
    else {
        print "Error! The default gateway could not be set.\n";
    }
}

This code has been viewed 998 times.

New from the creators of TechTasks.com: StatSheet.com