You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Win11下如何让IPv4配置PowerShell脚本自动以管理员权限运行

自动提权的IP配置PowerShell脚本(Win11)

需求说明

  • IP规则:
    • 主机名以s1结尾时,IP最后段设为10,前缀沿用当前IPv4的前三网段
    • 其他主机名(如cho-ryn-k1)提取数字部分,IP最后段设为20X(X为提取的数字,k1对应201,k2对应202)
  • 固定配置:
    • 子网掩码:255.255.255.0
    • DNS服务器:8.8.8.8、1.1.1.1
    • 双网关:与当前IPv4前三网段一致,结尾分别为254、253

问题痛点

Win11中直接右键运行PowerShell脚本默认以普通权限启动,无权限修改网络配置;需实现无需手动打开管理员PowerShell粘贴代码,直接从U盘运行脚本即可自动获取管理员权限执行。

解决方案脚本

# 检查并自动获取管理员权限
if (-not ([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)) {
    $arguments = "& '" + $MyInvocation.MyCommand.Definition + "'"
    Start-Process powershell -Verb RunAs -ArgumentList $arguments
    exit
}

# 原有IP配置逻辑
$hostname = hostname
$currentIP = (Get-WmiObject Win32_NetworkAdapterConfiguration | Where-Object { $_.IPAddress -ne $null -and $_.IPEnabled -eq $true }).IPAddress[0]
$firstThreeOctets = $currentIP -replace '\.\d+$', ''

if ($hostname -like "*s1") {
    $desiredIP = "$firstThreeOctets.10"
} else {
    $number = $hostname -replace '[^0-9]', ''
    $desiredIP = "$firstThreeOctets.20$number"
}

$adapter = Get-WmiObject Win32_NetworkAdapterConfiguration | Where-Object { $_.IPAddress -ne $null -and $_.IPEnabled -eq $true }
$adapter.EnableStatic($desiredIP, "255.255.255.0") | Out-Null

$dnsServers = "8.8.8.8", "1.1.1.1"
$adapter.SetDNSServerSearchOrder($dnsServers) | Out-Null

$gateway1 = "$firstThreeOctets.254"
$gateway2 = "$firstThreeOctets.253"
$gateways = @($gateway1, $gateway2)
$adapter.SetGateways($gateways) | Out-Null

# 配置结果输出
Write-Host "Stworzono przez " -NoNewline
Write-Host "Maksymilian Gawron" -ForegroundColor Red -NoNewline
Write-Host " dla wdrozen aptek " -NoNewline
Write-Host "Bankleku" -ForegroundColor Blue
Write-Host "Nazwa komputera: " -NoNewline
Write-Host "$hostname" -ForegroundColor Green
Write-Host "Obecny adres: " -NoNewline
Write-Host "$desiredIP" -ForegroundColor Green
Write-Host "Maska: " -NoNewline
Write-Host "255.255.255.0" -ForegroundColor Green
Write-Host "Brama 1: " -NoNewline
Write-Host "$gateway1" -ForegroundColor Green
Write-Host "Brama 2: " -NoNewline
Write-Host "$gateway2" -ForegroundColor Green
Write-Host "DNSy: " -NoNewline
Write-Host "$dnsServers" -ForegroundColor Green

使用说明

  1. 将上述脚本保存为Set-IPConfig.ps1,存入U盘根目录
  2. 在Win11设备上插入U盘,双击该脚本文件
  3. 系统会弹出UAC权限请求,点击「是」即可自动以管理员权限完成网络配置

脚本说明

  • 自动提权逻辑:脚本启动时先检查当前运行权限,若未获得管理员权限则自动重启并触发UAC权限申请
  • IP配置逻辑:完全保留原需求中的规则,自动根据主机名生成目标IP,并配置子网掩码、DNS及双网关
  • 结果验证:脚本执行完成后会输出所有配置信息,方便快速确认配置是否正确

内容的提问来源于stack exchange,提问作者Max Gavron

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.14 20:25:57