Archive

Archive for April, 2010

Export DHCP scopes and their address pools to a csv file

Because I love regular expressions, and I had a need for it, I have modified my previously posted DHCP export script:

$a = (netsh dhcp server 1.1.1.1 show scope)

$lines = @()
#start by looking for lines where there is IP present
foreach ($i in $a){
    if ($i -match "\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}"){
            $lines += $i.Trim()
    }
}

$csvfile = @()
$lines2 = @()
foreach ($l in $lines){
    $Row = "" | select Subnet,SubNetMask,ScopeStart,ScopeEnd,Location
    $l = $l + "`n"
    $l = $l -replace '-Active',''
    $l = $l -replace '-',','
    $l = $l -replace '\s',''
    $Row.Subnet = ($l.Split(","))[0]
    $c = $Row.Subnet
    $Row.SubNetMask = ($l.Split(","))[1]
    $Row.Location = ($l.Split(","))[2]
    $b = (netsh dhcp server 1.1.1.1 scope $c show iprange)
    foreach ($i2 in $b){
        if ($i2 -match "\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}" -and $i2 -notmatch 'Changed the current scope context to' `
            -and $i2 -notmatch 'No of IP Ranges : 1 in the Scope'){
            $lines2 += $i2.Trim()
        }
    }
    Foreach ($l2 in $lines2){
        $l2 = $l2 -replace '-',','
        $l2 = $l2 -replace '\s',''
        $Row.ScopeStart = ($l2.Split(","))[0]
        $Row.ScopeEnd = ($l2.Split(","))[1]
    }
    $csvfile += $Row
}    
$csvfile | sort-object Subnet | Export-Csv "C:\Users\Public\Documents\DHCPExport.csv"

The script put all the server scopes into a variable and then processes it.

As the netsh output is filled with headers and other stuff, quite a number of trims and –replacements are done.

The whole thing is then put into a csv file.

As usual any hints and pointers are welcomed.

/theadminguy

%d bloggers like this: