学习 / 批处理 · 2024年3月25日 0

powershell脚本设置自动获取或者静态IP

代码如下

#查看权限 
#Get-ExecutionPolicy
# 无执行权限:Restricted
#Set-ExecutionPolicy Restricted
#开启powershell执行权限
#Set-ExecutionPolicy remotesigned 
 
 
######
function judge-IsAdmin {
    return ([Security.Principal.WindowsPrincipal] [Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole(
            [Security.Principal.WindowsBuiltInRole] "Administrator")
}
if (!(judge-IsAdmin)) {
   Write-Host "任意键继续下一步,点是,会管理身份运行powershell窗,若闪退,请开启执行策略(Set-ExecutionPolicy remotesigned)"
   Write-Host "下一步同时会生成相同功能的批处理setmyip.cmd,若不会开启powershell执行策略可以用批处理"
   cmd /c pause
}
 
######
function Generate-cmds(){
$cmdContent = @"
@echo off
if not exist netinf.txt (
echo 192.168.10.113 > netinf.txt
echo 255.255.240.0 >> netinf.txt
echo 192.168.0.250 >> netinf.txt
echo 202.96.128.86 >> netinf.txt
echo 202.96.128.166 >> netinf.txt
)
goto mychoces
:mychoces
netsh interface ipv4 show config
echo "修改netinf.txt文件为要设的IP信息"
set /p name="设置接口的名字:"
set /p chosse="设置自动获取/静态IP(Y/N):"
if "%chosse%"=="y" (goto autoip )
if "%chosse%"=="Y" (goto autoip )
if "%chosse%"=="N" (goto setmyip )
if "%chosse%"=="n" (goto setmyip )
goto mychoces
:autoip
netsh interface ip set address name=%name% source=dhcp
netsh interface ip set dns name=%name% source=dhcp
goto mychoces
:setmyip
setlocal enabledelayedexpansion
set dp=%~dp0
set "filename=netinf.txt"
set "index=0"
for /F "tokens=*" %%L in (%dp%%filename%) do (
    set "line[!index!]=%%~L"
    set /A index+=1 
)
 
netsh interface ipv4 set address name=%name% static !line[0]! !line[1]! !line[2]!
netsh interface ipv4 set dns name=%name% static !line[3]! primary
netsh interface ipv4 add dns name=%name% !line[4]! index=2
endlocal
goto mychoces
 
"@
$cmdFileName = "setmyip.cmd"
Set-Content -Path $cmdFileName -Value $cmdContent  
Write-Host "已生成相同功能的批处理$($cmdFileName)"
 
}
#####
 
###
$hascommand = Get-Command -Name "Get-CimInstance" -ErrorAction SilentlyContinue
if(!$hascommand){
Write-Host "powershell版本太低"
Generate-cmds
cmd /c pause | out-null  
exit
}else{
####
Generate-cmds
 
#
#Start-Process cmd -ArgumentList "/k", $cnds
}
#####
 
$filePath ="netinf.txt"
 
if (!(Test-Path -Path $filePath)){
$intlines = @("192.168.10.110", "255.255.240.0", "192.168.0.250","202.96.128.86","202.96.128.166") 
foreach ($iline in $intlines) {
    Add-Content -Value $iline -Path $filePath 
}
}
 
$p1=(Get-Location).path
$fip=Join-Path -Path $p1 -ChildPath "setip.ps1"
 
  
if (-not (judge-IsAdmin)) {
    # 如果不是管理员,则以管理员权限重新启动当前脚本
    Start-Process PowerShell -Verb RunAs -ArgumentList ("-noprofile -file `"{0}`"" -f ($myinvocation.MyCommand.Definition)) 
    exit
}
 
Function Convert-MaskToCIDR {
    param (
        [Parameter(Mandatory = $true)]
        [IPAddress] $SubnetMask
    )
 
    [String] $binaryString = @()
    $SubnetMask.GetAddressBytes() | ForEach-Object { $binaryString += [Convert]::ToString($_, 2) }
 
    Return $binaryString.TrimEnd('0').Length
}
 
$q=""
#$aa=@()
while ($q -ne "Q"){
 
$ips=Get-CimInstance -Class Win32_NetworkAdapterConfiguration
 
foreach($ip in $ips){
if($ip.IPAddress){
Write-Host "Description:$($ip.Description) "
Write-Host "InterfaceIndex:$($ip.InterfaceIndex) "
Write-Host "DHCP:$($ip.DHCPEnabled) "
Write-Host "IP:$($ip.IPAddress) "
Write-Host "Gateway:$($ip.DefaultIPGateway) "
Write-Host "IPSubnet:$($ip.IPSubnet)  "
Write-Host "DNS:$($ip.DNSServerSearchOrder) "
Write-Host "---------------------------------------"
#$aa.add(@{"index"=$ip.InterfaceIndex,"dhcp"=$ip.DHCPEnabled})
}
 }
   
 
 
Write-Host "修改IP配置文件netinf.txt为要设置的IP信息"
 
$userindex=Read-Host "要配置的选项InterfaceIndex:"
$isdhcp=Read-Host "(Y/N)自动获取/静态IP:"
if($isdhcp -eq "Y")
{
$ne=Get-NetIPInterface -InterfaceIndex $userindex
if($ne.dhcp[1] -eq "Disabled"){
  
Remove-NetIPAddress -InterfaceIndex $userindex  -Confirm:$false
Remove-NetRoute -InterfaceIndex $userindex  -Confirm:$false 2>$null
Set-NetIPInterface -InterfaceIndex $userindex -Dhcp Enabled
Set-DnsClientServerAddress -InterfaceIndex $userindex -ResetServerAddresses
#Invoke-Expression "ipconfig /renew"
$ne1=Get-NetIPInterface -InterfaceIndex $userindex
Write-Host "DHCP:$($ne1.dhcp[1])"
Get-NetIPConfiguration -Verbose -InterfaceIndex $userindex
}else{
Write-Host "已经是自动获取"
}
}
if($isdhcp -eq "N")
{
$p2=Split-Path -Parent $MyInvocation.MyCommand.Definition
$finf=Join-Path -Path $p2 -ChildPath $filePath
#Write-Host $finf
$lines = Get-Content -Path $finf
#Write-Host $lines
#Get-NetIPAddress -InterfaceIndex $userindex | Remove-NetIPAddress
Remove-NetIPAddress -InterfaceIndex $userindex  -Confirm:$false
Remove-NetRoute -InterfaceIndex $userindex  -Confirm:$false 2>$null
$plen=Convert-MaskToCIDR $lines[1]
New-NetIPAddress -InterfaceIndex $userindex -IPAddress $lines[0] -AddressFamily IPv4 -PrefixLength $plen -DefaultGateway $lines[2] >$null
 
Set-DnsClientServerAddress -InterfaceIndex $userindex -ServerAddresses $lines[3,4]
Get-NetIPConfiguration -Verbose -InterfaceIndex $userindex
}
 
$q=Read-Host "输入Q退出"
 
}