在我的办公室(大约7000台电脑),每台电脑都有一个IPv4预留,用于安全措施。
如果计算机被替换,则需要清理保留,但它可能在多个作用域中。
我创建了一个脚本,它在每个作用域中搜索您提供的MAC地址,但在找不到该MAC地址的每个作用域也会生成一个错误。
删除IP保留有效,但我希望脚本执行以下操作:首先,它应该在作用域列表中搜索计算机所在的正确作用域,然后执行实际删除保留的代码。
此外,当在任何范围内都找不到MAC地址时,我尝试给出一个文本输出,但这似乎也不起作用。
这是我的代码:
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
试试这样的东西(这是我用来做类似事情的方法):
$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)
}
}
}
让PowerShell为您完成所有繁重的工作:
$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."
}
以上假设输入的MAC地址具有##-##-##-##-##-##
的形式。如果您也想允许使用冒号(##:##:##:##:##:##
),则在使用Where-Object
筛选器中的地址之前,需要将冒号替换为连字符:
$mac = $mac -replace ':', '-'