koi1 发表于 2024-3-25 14:12

powershell脚本设置自动获取或静态IP(含批处理)

本帖最后由 koi1 于 2024-4-2 09:38 编辑

powershell脚本设自动获取或静态IP,
要管理员身份运行才可以修改,脚本已设置管理员身份打开,
而管理员身份打开运行powershell脚本要开启执行策略(Set-ExecutionPolicy remotesigned),默认没有开启。
运行此ps脚本会生成一个静态IP文件netinf.txt,修改这个文件为自已要设置的静态IP各项就可以(或者直接改脚本里面的默认生成),不要增加别的其他东西。
也同时生成可设置自动获取或静态IP的批处理。

保存为xxx.ps1右键使用powershell运行

#查看权限
#Get-ExecutionPolicy
# 无执行权限:Restricted
#Set-ExecutionPolicy Restricted
#开启powershell脚本执行权限
#Set-ExecutionPolicy remotesigned


######
function judge-IsAdmin {
    return ( ::GetCurrent()).IsInRole(
             "Administrator")
}
if (!(judge-IsAdmin)) {
   Write-Host "任意键继续下一步,点是,会管理身份运行powershell窗,若闪退,请开启执行策略(Set-ExecutionPolicy remotesigned)"
   Write-Host "下一步同时会生成相同功能的批处理setmyip.cmd,若不会开启powershell执行策略可以用批处理"
   cmd /c pause
}

######
function Generate-cmds(){
$cmdContent = @"
@echo off
set dp=%~dp0
if not exist %dp%netinf.txt (
echo 192.168.10.113> %dp%netinf.txt
echo 255.255.240.0>> %dp%netinf.txt
echo 192.168.0.250>> %dp%netinf.txt
echo 202.96.128.86>> %dp%netinf.txt
echo 202.96.128.166>> %dp%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 "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! !line! !line!
netsh interface ipv4 set dns name=%name% static !line! primary
netsh interface ipv4 add dns name=%name% !line! 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 (
      
       $SubnetMask
    )

    $binaryString = @()
    $SubnetMask.GetAddressBytes() | ForEach-Object { $binaryString += ::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 -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)"
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
New-NetIPAddress -InterfaceIndex $userindex -IPAddress $lines -AddressFamily IPv4 -PrefixLength $plen -DefaultGateway $lines >$null

Set-DnsClientServerAddress -InterfaceIndex $userindex -ServerAddresses $lines
Get-NetIPConfiguration -Verbose -InterfaceIndex $userindex
}

$q=Read-Host "输入Q退出"

}



运行图片;

Marken888 发表于 2024-3-25 16:07

感谢源码分享!

Shatskikh 发表于 2024-3-25 23:43

PowerShell的一个好处是可以把之前的命令也放到脚本里执行
页: [1]
查看完整版本: powershell脚本设置自动获取或静态IP(含批处理)