I work for a School District and we have 60 school sites. I am attempting to bulk add DHCP scopes to each site using powershell so I don’t have to click through the GUI for each scope. I am needing to run the (3) following commands to add the scope and associated options but would like to capture data from a CSV to add the scope to all 60 sites:
Add-DhcpServerv4Scope -cn dhcp1 -Name "PAH IOT" -StartRange 10.123.112.2 -EndRange 10.123.119.254 -SubnetMask 255.255.248.0 -LeaseDuration 4.00:00:00;
Set-DhcpServerv4OptionValue -cn "dhcp1" -ScopeId 10.123.112.0 -DnsServer 10.2.10.95,10.2.10.96 -Router 10.123.112.1 -DnsDomain mydomain.net;
Add-DhcpServerv4FailoverScope -cn "dhcp1" -Name "dhcp1.mydomain.net-dhcpfailover1.mydomain.net" -ScopeId 10.123.112.0
This is literally my first attempt at Powershell, so don’t mind my script…but it failed miserably. I created a CSV with the following headers and attempted to reference them in the script as a variable.
Server,ScopeName,StartIP,EndIP,Mask,Lease,ScopeID,Router,DNS,Failover
dhcp1,PAHIOT,10.123.112.2,10.123.119.254,255.255.248.0,4.00:00:00,10.123.112.0,10.123.112.1,10.2.10.95,dhcp1.mydomain.net-dhcpfailover1.mydomain.net
$Scopes = import-csv "$env:OneDrive - \desktop\DHCP\Scopes.csv"
Foreach ($Scope in $Scopes) {
Add-DhcpServerV4Scope -Computername $_.server -Name $_.ScopeName -StartRange $_.StartIP -EndRange $_.EndIP -SubnetMask $_.Mask -LeaseDuration $_.Lease
Set-DhcpServerV4OptionValue -ComputerName $_.Server -ScopeID $_.ScopeID -DNSServer $_.DNS -Router $_.Router -DnsDomain mydomain.net
Add-DhcpServerv4FailoverScope -CN $_.Server -Name $_.Failover -ScopeID $_.ScopeID
}
What I am attempting to do is fill out the CSV with information for all 60 of my sites with the required information and run the script to have all the DHCP scopes with my required options set. I was thinking that the $_. function would call to the associated header and use the value as the variable and process each line ($Scopes) through the end of the CSV. Any help would be appreciated! Thanks.
5
Use the $Scope
iterator variable you declared in the foreach
statement:
$Scopes = Import-Csv "$env:OneDrive - \desktop\DHCP\Scopes.csv"
foreach ($Scope in $Scopes) {
Add-DhcpServerV4Scope -Computername $Scope.Server -Name $Scope.ScopeName -StartRange $Scope.StartIP -EndRange $Scope.EndIP -SubnetMask $Scope.Mask -LeaseDuration $Scope.Lease
Set-DhcpServerV4OptionValue -ComputerName $Scope.Server -ScopeID $Scope.ScopeID -DNSServer $Scope.DNS -Router $Scope.Router -DnsDomain mydomain.net
Add-DhcpServerv4FailoverScope -CN $Scope.Server -Name $Scope.Failover -ScopeID $Scope.ScopeID
}