在powershell中将当前DHCP IPv4设置为静态

时间:2017-03-14 01:21:36

标签: powershell

有没有办法让当前的IPv4地址分配给PC并使用脚本将其设置为静态?

脚本必须能够从有线接口获取当前活动的IPv4,然后提供将其设置为静态的选项

如果可能,请使脚本在将其设置为静态后还可以选择还原到DHCP。

谢谢

1 个答案:

答案 0 :(得分:2)

这里我试着为你写一个很好的代码

#Setting up the interface t get the address from
clear-host
write-host
Write-Host "   |-------------------------------------------------|"
Write-Host "   |                                                 |"
Write-Host "   |     Welcome ... -help by Aayush Kharel          |"
Write-Host "   |                                                 |"
Write-Host "   |-------------------------------------------------|"
write-host
write-host "You have following interfaces in you computer ..."
$intalias = (get-netadapter).interfacealias
for ($i=1; $i -le $intalias.length; $i++) 
{
    $temp = $intalias.get($i-1)
    write-host "   $i. $temp "
}
write-host
$selectedinterfacenum = read-host "Select the number of the interface you want to use"
$interfacealias = $intalias.get($selectedinterfacenum - 1)
write-host
write-host " You selected $interfacealias ..."
write-host
$interface = get-netipconfiguration -interfacealias $interfacealias
#Get ipv4 address
$ipaddress = $interface.ipv4address.ipv4address
#get default gateway
$ipgateway = $interface.ipv4defaultgateway.nexthop
#to get the subnet mask we need to use wmi object
$interface2 = get-wmiobject -class win32_networkadapterconfiguration | where-object {$_.defaultipgateway -ne $null}
#Getting the subnet mask
$ipsubnet = $interface2.ipsubnet | select-object -first 1
#We have to convert subnet mask to cidr notation
$mask = $ipsubnet.split(".")
$cidr = [int] 0
$octet = [int] 0
foreach ($octet in $mask) {
    if ($Octet -eq 255){$CIDR += 8}
    if ($Octet -eq 254){$CIDR += 7}
    if ($Octet -eq 252){$CIDR += 6}
    if ($Octet -eq 248){$CIDR += 5}
    if ($Octet -eq 240){$CIDR += 4}
    if ($Octet -eq 224){$CIDR += 3}
    if ($Octet -eq 192){$CIDR += 2}
    if ($Octet -eq 128){$CIDR += 1}
} #end foreach
#Output
write-host Your IPv4 Address from DHCP is 
write-host "   Address  $ipaddress"
write-host "   Subnet   $ipsubnet"
write-host "   Gateway  $ipgateway"
write-host "   CIDR     $cidr"
write-host
$answer = read-host "Do you want to set it as static ? (Y/N) "
write-host
if ($answer -eq "y") 
{
    write-host "Setting up the address to static ..."
    remove-netipaddress -interfacealias $interfacealias -addressfamily ipv4
    new-netipaddress -interfacealias $interfacealias -ipaddress $ipaddress -prefixlength $cidr -defaultgateway $ipgateway
    write-host "Your ip address is now static ..."
}
else {write-host " You choose not to set it as static ... " }

write-host #theEnd

将脚本另存为ps1并运行它 如果您对此有任何疑问,请与我们联系。谢谢