在Windows服务器上添加其他IP地址

时间:2017-10-05 13:55:07

标签: windows powershell batch-file scripting

是否可以使用powershell或在C:\Windows\addExtraIP.bat下使用bat脚本,该脚本使用多个参数将IP地址添加到接口/连接。

想法是使用类似的东西:

addExtraIP.bat 192.168.1.2 192.168.1.3 192.168.1.4 and so on..

应该从远程调用/调用此addExtraIP.bat脚本。我读了一些关于PowerShell remoting的内容,但不确定从哪里开始或做什么。

有什么想法吗?提前谢谢!

编辑:

function Set-IPAddress {
        param(  [string]$networkinterface = "Local Area Connection",
            [string]$ip, 
            [string]$mask,
            [string]$gateway, 
            [string]$dns1 = "8.8.8.8",
            [string]$dns2 = "8.8.4.4",
            [string]$registerDns = "TRUE"
     )


     #Start writing code here
     $dns = $dns1
     if($dns2){$dns =$dns1,$dns2}
     $index = (gwmi Win32_NetworkAdapter | where {$_.netconnectionid -eq $networkinterface}).InterfaceIndex
     $NetInterface = Get-WmiObject Win32_NetworkAdapterConfiguration | where {$_.InterfaceIndex -eq $index}
     $NetInterface.EnableStatic($ip, $mask)
     $NetInterface.SetGateways($gateway)
     $NetInterface.SetDNSServerSearchOrder($dns)
     $NetInterface.SetDynamicDNSRegistration($registerDns)

 }

 Set-IPAddress

这个脚本就是我想要使用的。如何调用上面提到的脚本?

编辑2:

function Set-IPAddress {
        param(
            [string]$networkinterface = "Local Area Connection",
            [string[]]$ip, 
            [string[]]$mask,
            [string]$gateway, 
            [string]$dns = @("10.210.1.101", "10.210.1.130"),
            [bool]$registerDns = $true
     )


     $index = (gwmi Win32_NetworkAdapter | where {$_.netconnectionid -eq $networkinterface}).InterfaceIndex
     $NetInterface = Get-WmiObject Win32_NetworkAdapterConfiguration | where {$_.InterfaceIndex -eq $index}
     $NetInterface.EnableStatic($ip, $mask)
     $NetInterface.SetGateways($gateway)
     $NetInterface.SetDNSServerSearchOrder($dns)
     $NetInterface.SetDynamicDNSRegistration($registerDns)

 }

 Set-IPAddress -IP '1.2.3.4', '2.3.4.5' -Mask '255.255.255.0', '255.255.255.0'

那么我如何在脚本中设置它并运行,无论传递多少参数?

1 个答案:

答案 0 :(得分:1)

使用New-NetIPAddress的基本foreach循环:

param([array]$IPs)

Foreach ($IP in $IPs)
{
    New-NetIPAddress -InterfaceIndex 12 -IPAddress $IP -PrefixLength 24 -DefaultGateway 192.168.0.5
}

然后打电话给:

ScriptName.ps1 -IPs 192.168.0.1,192.168.0.2