You are here:   Research
  |  Login

Welcome to my blog, quickest way to find articles is usually to search for them.

Minimize
Search in All Title Contents
 
     

Automate DHCP Server Configuration via PowerShell

Aug 27 2017

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, @AdaptivaAmi, who requested it :)

You run the script on the Hyper-V host

# Set some variables
$VMName = "OSD-1607-TP-PC0001"
$IPAddress = "192.168.1.17"
$DHCPDescription = "TP Clients"
$DHCPServer = "DC01"
$DHCPScopeID = "192.168.0.0"
$Username = 'VIAMONSTRA\Administrator'
$Password = 'P@ssw0rd'

# Get the Mac Address from a VM and format it (add - in between the pairs of hexadecimal digits)
$Mac = (Get-VMNetworkAdapter -VMName $VMName ).MacAddress
$Mac = $Mac -replace '..(?!$)', '$&-'

# Print the Mac Address
# Write-Output $Mac

# 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, $Mac, $IPAddress, $DHCPDescription, $VMName)
    Add-DhcpServerv4Reservation -ScopeId $DHCPScopeID -ComputerName "$DHCPServer" -ClientId $Mac -IPAddress $IPAddress -Description $DHCPDescription -Name $VMName
} -ArgumentList ($DHCPScopeID, $DHCPServer, $Mac, $IPAddress, $DHCPDescription, $VMName)

Here is the result on the DHCP server

DHCP01
The static reservation added to the DHCP Server.

And the result on the client

DHCP02
The end result on the virtual machine client.

Written by Johan Arwidmark








Happy deployment, and thanks for reading!


What our lawyers makes us say:

This information is provided "AS IS" with no warranties, confers no rights and is not supported by the authors or Deployment Artist.

Copyright © 2017 by Deployment Artist (the company behind deployment research). All rights reserved. No part of the information on this web site may be reproduced or posted in any form or by any means without the prior written permission of the publisher.

Shorthand: Don't pass off our work as yours, it's not nice.

Blog Archive

Minimize