使用DNS在远程电脑上静态配置IP



我有这个powershell脚本,可以在当前使用DHCP接收IP的远程电脑上静态设置IP。因此,脚本可以设置IP,但由于它在不同的VLAN上,它会断开连接,无法完成DNS部分。如何让它同时设置IP和DNS,然后断开连接?

$IP = 192.168.1.10
$Machine = "Server1"
$Mask = 24
$Gateway = "192.168.1.1"
$DNS = "8.8.8.8", "1.1.1.1"

Get-NetAdapter -name 'Ethernet0 3' -CimSession $Machine | Set-DNSClientServerAddress -ServerAddresses $DNS
Get-NetAdapter -name 'Ethernet0 3' -CimSession $Machine | new-NetIPAddress -IPAddress $IP -PrefixLength $Mask -Defaultgateway $Gateway

不要引用可能在命令之间关闭的特定CimSession,而是尝试用多个命令启动远程断开连接的PSSession:

$DCS = Invoke-Command -ComputerName $ComputerName -InDisconnectedSession -ScriptBlock {
Get-NetAdapter -name 'Ethernet0 3' | Set-DNSClientServerAddress -ServerAddresses $Using:DNS
Get-NetAdapter -name 'Ethernet0 3' | New-NetIPAddress -IPAddress $Using:IP -PrefixLength $Using:Mask -Defaultgateway $Gateway
}

然后,您可以尝试重新连接会话-要么从您运行的命令中接收任何输出,要么从您停止的地方继续。这可能会在通过更改IP时出现错误

sleep $seconds
# Requires your PC to be able to resolve the old computer name to the new address:
Receive-PSSession $DCS
# Sometimes works better to get an updated session object first:
Get-PSSession $DCS | Receive-PSSession
# If nothing else, you can get the session object again with the new IP. 
# This requires HTTPS winrm, and explicit credentials:
Get-PSSession -ComputerName $IP -UseSSL -Credential (Get-Credential)

最新更新