Automate DHCP Server Configuration via PowerShell

Here is a quick sample on using PowerShell to create static reservation in DHCP for a given virtual machine. This is for a typical Hyper-V Lab scenario, and it was my better half, Ami, who requested it 🙂

You run the script on the Hyper-V host

# Set some variables
$VMName = "OSD-1607-TP-PC0001"
$IPAddress = ""
$DHCPDescription = "TP Clients"
$DHCPServer = "DC01"
$DHCPScopeID = ""
$Username = 'VIAMONSTRA\Administrator'
$Password = '[email protected]'

# Get the Mac Address from a VM and format it (add - in between the pairs of hexadecimal digits)
$Mac = (Get-VMNetworkAdapter -VMName $VMName ).MacAddress
$FormattedMac = $Mac.insert(2,"-").insert(5,"-").insert(8,"-").insert(11,"-").insert(14,"-")

# Print the Mac Address 
Write-Output $FormattedMac 

# Set credentials and allow remote administration via PowerShell to all hosts
winrm set winrm/config/client '@{TrustedHosts="*"}' | Out-Null 
$pass = ConvertTo-SecureString -AsPlainText $Password -Force 
$Cred = New-Object System.Management.Automation.PSCredential -ArgumentList $Username,$pass 
# Connect to the DCHP Server and add the reservation 
Invoke-Command -ComputerName $DHCPServer -Credential $Cred -ScriptBlock { param($DHCPScopeID, $DHCPServer, $FormattedMac, $IPAddress, $DHCPDescription, $VMName) Add-DhcpServerv4Reservation -ScopeId $DHCPScopeID -ComputerName "$DHCPServer" -ClientId $FormattedMac -IPAddress $IPAddress -Description $DHCPDescription -Name $VMName } -ArgumentList ($DHCPScopeID, $DHCPServer, $FormattedMac, $IPAddress, $DHCPDescription, $VMName)

Here is the result on the DHCP Server

The static reservation added to the DHCP Server.

And the result on the client

The end result on the virtual machine client.

Written by Johan Arwidmark

About the author

Johan Arwidmark

0 0 votes
Article Rating
Notify of
Inline Feedbacks
View all comments