修改hosts文件(判断是否为管理员/以管理员权限运行脚本)
将以下命令保存为 HostsModify.ps1,然后执行即可
1 #该脚本用来添加hosts解析记录。脚本在执行的时候会判断当前用户是否为管理员,如果不是则弹出提示框口,要求输入相应密码 2 If (-NOT ([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator")) 3 { 4 $arguments = "& '" + $myinvocation.mycommand.definition + "'" 5 Start-Process powershell -Credential administrator -WindowStyle Hidden -ArgumentList $arguments 6 Break 7 } 8 9 #下面为要执行的命令 10 #在hosts中添加解析记录 11 $line = "127.0.0.1 www.sapien.com" 12 $file = "$env:windir\system32\drivers\etc\hosts" 13 out-file -InputObject $line -filepath $file -append -Encoding default
删除hosts中添加的解析记录
1 #删除hosts中添加的解析记录 2 $line = "127.0.0.1 www.sapien.com" 3 $file = "$env:windir\system32\drivers\etc\hosts" 4 #$contents = gc $file | ? {!($_.contains($line))} #选择不包含$line的行 5 $contents = gc $file | ? {$_ -ne $line} #选择不等于$line的行 6 clear-content $file 7 out-file -InputObject $contents -filepath $file -append -Encoding default
###################################################
脚本直接以管理员权限运行(将管理员账户和密码写入脚本中)
1 #该脚本用来在hosts文件中添加解析记录。如果当前用户不是管理员,则会直接以管理员权限运行(可以将管理员账户和密码写入脚本中) 2 If (-NOT ([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator")) 3 { 4 $UserName = "administrator" #定义管理员账户名称 5 $serverpass = "cmr" #定义管理员账户密码 6 $Password = ConvertTo-SecureString $serverpass -AsPlainText –Force 7 $cred = New-Object System.Management.Automation.PSCredential($UserName,$Password) 8 $arguments = "& '" + $myinvocation.mycommand.definition + "'" 9 Start-Process powershell -Credential $cred -WindowStyle Hidden -ArgumentList $arguments 10 Break 11 } 12 13 #下面为要执行的脚步命令 14 #在hosts中添加解析记录 15 $line = "127.0.0.1 www.sapien.com" 16 $file = "$env:windir\system32\drivers\etc\hosts" 17 out-file -InputObject $line -filepath $file -append -Encoding default
Start-Process -Verb runas 这里的 runas是以管理员权限运行,但是前提是当前用户必须已经是管理员,效果等同于:
参考:http://www.pstips.net/force-script-run-as-admin.html
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?