Reputation: 21
At my office (about 7000 computers) every PC has an IPv4 reservation for security measures.
If a computer is replaced the reservation needs to be cleaned, but there are multiple scopes that it could be in.
I've created a script which searches for the MAC address you provide, through every scope but also generates an error at every scope where that MAC address is not found.
The removing of the IP reservation works but what I want the script to do is the following: First it should search the list of scopes for the correct scope which the computer is in, then it should execute the code in which it actually removes the reservation.
Also, I tried giving a text output for when the MAC adress is not found in any scope at all, but that doesn't seem to work either.
Here's my code:
Write-Host "remove mac-address"
$Mac = Read-Host "Mac-Adres"
$ScopeList = Get-Content sometxtfilewithscopes.txt
foreach($Scope in $Scopelist)
{
Remove-DhcpServerv4reservation -ComputerName #ipofdhcpserver# -ClientId $Mac -ScopeId $scope -erroraction SilentlyContinue -PassThru -Confirm -OutVariable NotFound | Out-Null
}
if ($NotFound -eq $false ) {
Write-Host "MAC-address not found!"
}
pause
Upvotes: 2
Views: 4334
Reputation: 200233
Just let PowerShell do all the heavy lifting for you:
$mac = Read-Host 'Enter MAC address'
$server = 'yourdhcpserver'
$reservation = Get-DhcpServerv4Scope -Computer $server |
Get-DhcpServerv4Reservation -Computer $server |
Where-Object { $_.ClientId -eq $mac }
if ($reservation) {
$reservation | Remove-DhcpServerv4Reservation -Computer $server
} else {
"$mac not found."
}
The above assumes that the entered MAC address has the form ##-##-##-##-##-##
. If you want to allow colons as well (##:##:##:##:##:##
) you need to replace the colons with hyphens before using the address in the Where-Object
filter:
$mac = $mac -replace ':', '-'
Upvotes: 1
Reputation: 1242
Try something like this (this is what I use for something similar):
$mac = Read-Host "Enter MAC Address"
if ($mac -eq $null) { Write-Error "No MAC Address Supplied" -ErrorAction Stop }
$ServerName = "mydhcpserver.mydomain.net"
$ScopeList = Get-DhcpServerv4Scope -ComputerName $ServerName
ForEach ($dhcpScope in $ScopeList) {
Get-DhcpServerv4Reservation -ScopeId $dhcpScope.ScopeId -ComputerName $ServerName | `
Where {($_.ClientID -replace "-","").ToUpper() -eq $mac.ToUpper()} | `
ForEach {
Try {
Remove-DhcpServerv4Reservation -ClientId $_.ClientID -ScopeId $dhcpScope.ScopeId -Server $ServerName -WhatIf
} catch {
Write-Warning ("Error Removing From Scope" + $dhcpScope.ScopeId)
}
}
}
Upvotes: 1