请教大家,利用WMI修改IP,网关,DNS的问题
以下是使用PowerShell处理的脚本
使用方法:
先将自定义Function的代码运行一次.
然后用你希望的内容替换掉""里的说明但保留""并运行命令.
另外在修改远程计算机时会弹出要求输出账户密码的对话框,请输入拥有远程计算机权限的账号和密码.
以下为PowerShell代码
修改本机:
Set-StaticIPAddress -ComputerName LocalHost -IPAddress "设定后的IP地址" -SubnetMask "子网" -DefaultGateway "默认网关" -DNSServers "DNS服务器地址"
修改远程计算机:
Set-StaticIPAddress -ComputerName "要修改的计算机名或者IP地址" -IPAddress "设定后的IP地址" -SubnetMask "子网" -DefaultGateway "默认网关" -DNSServers "DNS服务器地址" -Credential (Get-Credential)
#以下为自定义Function代码
Function Set-StaticIPAddress
{
param
(
[Parameter(Mandatory = $true,
Position = 0,
ValueFromPipeline = $true,
ValueFromPipelineByPropertyName = $true)]
[String] $ComputerName
,
[Parameter(Mandatory = $true,
Position = 1)]
[Alias("IPv4Address")]
[String] $IPAddress
,
[Parameter(Position = 2)]
[String] $SubnetMask = "none"
,
[Parameter(Position = 3)]
[String] $DefaultGateway = "none"
,
[Parameter(Position = 4)]
[String[]] $DNSServers = ("172.16.1.36","172.16.1.78")
,
[Parameter(Position = 5)]
[PSCredential] $Credential
)
process
{
# There's some error-checking here that I've snipped out for convenience
Write-Verbose "Testing connection to $ComputerName"
if (-not (Test-Connection $ComputerName))
{
Write-Error "Unable to connect to $ComputerName."
return
}
Write-Verbose "Obtaining remote WMI reference"
if ($Credential)
{
$wmi = Get-WmiObject Win32_NetworkAdapterConfiguration -ComputerName $ComputerName -Filter "IPEnabled = 'True'" -Credential $Credential
} else {
$wmi = Get-WmiObject Win32_NetworkAdapterConfiguration -ComputerName $ComputerName -Filter "IPEnabled = 'True'"
}
Write-Verbose "Attempting to set DNS servers"
$wmi.SetDNSServerSearchOrder($DNSServers)
Write-Verbose "Attempting to set dynamic DNS registration"
$wmi.SetDynamicDNSRegistration($true)
Write-Verbose "Attempting to set static IP address and subnet mask"
$wmi.EnableStatic($IPAddress, $SubnetMask)
Clear-DnsClientCache #This may not be necessary; I added it as a troubleshooting step
Write-Verbose "Attempting to set default gateway"
$wmi.SetGateways($DefaultGateway, 1)
Write-Output $wmi
}
}
2023-07-25 广告