将适配器从静态 IP 更改为 DHCP

将适配器从静态 IP 更改为 DHCP

我想更改两个 AD OU 的所有计算机的接口。目前所有接口都有静态 IP 和 DNS 服务器。我写了这个 Powershell 脚本:

$getIP = get-netipaddress | Where-Object IPAddress -Like "192.168.18.*"
$index = $getip.InterfaceIndex
Get-NetIPInterface | where-Object InterfaceIndex -like "$index" | Set-NetIPInterface -Dhcp Enabled
$rep = Get-NetIPInterface | where-Object InterfaceIndex -like "$index"
$rep1 = $rep.InterfaceAlias
$Hostn = hostname
$Test = Get-NetIPInterface -InterfaceIndex $index | Where-Object {$_.Dhcp -like "Enabled"}
if ($Test){
$DHCPSTATUS = "DHCP active"
$report = "The Interface $Rep1 on $Hostn was set to DHCP . The DNS Server are resettet"
Set-DnsClientServerAddress -InterfaceIndex "$index" -ResetServerAddresses
}
else{
$DHCPSTATUS = "DHCP_not_active"
$report = "The Interface $Rep1 on $Hostn was NOT set to DHCP . The DNS Server are NOT resettet"
}
$report | Out-File \\Server\d$\DHCP\Result\$Hostn"_"$DHCPSTATUS.txt

对于这两个 OU,我使用 Startscript 启用了 GPO:[OU 图像链接][1]

当我运行 gpresult 时,它显示 GPO 已被使用,但是界面没有任何反应,也没有写入任何文本。[1]:https://i.stack.imgur.com/ZSZbV.png

答案1

尝试使用批处理而不是 PowerShell netsh 命令

netsh interface ip set dns "Local Area Connection" dhcp
netsh interface ip set address "Local Area Connection" dhcp
ipconfig /renew
ipconfig /registerdns

答案2

我尝试用利用 PowerShell 5.1 和标准 cmdlet 的更新脚本替换所有旧脚本,最终得到以下结果:

## Get the Physical NIC
$adapter = Get-NetAdapter -Physical

## Get the NIC Name as a System Variable
$nicName = $Adapter.Name

## Get the NIC Index
$nicIndex = $adapter.ifIndex

## Set the network interface to a variable for future use
$interface = Get-NetIPInterface -InterfaceIndex $nicIndex -AddressFamily IPv4

## Remove the static default gateway
Remove-NetRoute -InterfaceIndex $nicIndex -AddressFamily IPv4 -Confirm:$false

## Set interface to "Obtain an IP address automatically"
Set-NetIPInterface -InterfaceIndex $nicIndex -Dhcp Enabled

## Set interface to "Obtain DNS server address automatically"
$interface | Set-DnsClientServerAddress -ResetServerAddresses

## Sleep to allow some environments to process (older hardware)
Start-Sleep -Seconds 10

## Restart the NIC for Sanity
Restart-NetAdapter -Name $nicName -Confirm:$false -Verbose

## Sleep to allow some environments to process (older hardware)
Start-Sleep -Seconds 10

## Display new IP 
### (nice for me as I utilize this information but not needed)
$NewIP = (Get-NetIPAddress -InterfaceIndex $nicIndex).IPv4Address
$NewIP

## Register the adapter in DNS
Register-DnsClient -Verbose

## Flush the DNS cache
Clear-DnsClientCache -Verbose

相关内容