随笔 - 911  文章 - 5  评论 - 94  阅读 - 243万

修改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

posted on   momingliu11  阅读(3038)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

点击右上角即可分享
微信分享提示