2010-02-12 21:46:32 +0000 2010-02-12 21:46:32 +0000
63
63
Advertisement

如何以管理员身份运行 powershell 脚本

Advertisement

在我的 Windows 7 桌面上,我有一个脚本.ps1,它需要管理员权限(它启动了一个服务)。我想点击这个脚本,然后用管理员权限运行它。

有什么最简单的方法可以做到这一点?

Advertisement
Advertisement

答案 (7)

53
53
53
2010-02-13 12:58:54 +0000

这里有一个方法,就是在桌面上多了一个图标的帮助。我想,如果你想在桌面上只有一个图标,你可以把脚本移到别人那里去

  1. 在桌面上创建一个Powershell脚本的快捷方式
  2. 右键单击快捷方式,然后单击属性
  3. 点击快捷方式标签
  4. 单击高级 5.选择以管理员身份运行

现在你只需在桌面上双击新的快捷方式,就可以运行该脚本。

20
20
20
2013-01-10 17:29:06 +0000

在支持UAC的系统中,为了确保脚本在运行时有完整的管理权限,请在脚本的开头添加以下代码:

param([switch]$Elevated)

function Test-Admin {
  $currentUser = New-Object Security.Principal.WindowsPrincipal $([Security.Principal.WindowsIdentity]::GetCurrent())
  $currentUser.IsInRole([Security.Principal.WindowsBuiltinRole]::Administrator)
}

if ((Test-Admin) -eq $false) {
    if ($elevated) 
    {
        # tried to elevate, did not work, aborting
    } 
    else {
        Start-Process powershell.exe -Verb RunAs -ArgumentList ('-noprofile -noexit -file "{0}" -elevated' -f ($myinvocation.MyCommand.Definition))
}

exit
}

'running with full privileges'

当使用-elevated开关运行脚本时,它将在运行前尝试提升权限。

13
Advertisement
13
13
2010-11-27 11:48:43 +0000
Advertisement

如果你是在同一个 powershell中,你可以这样做:

Start-Process powershell -verb runas -ArgumentList "-file fullpathofthescript"
4
4
4
2010-02-12 22:02:27 +0000

既然它是在你的桌面上,我想说最省力的方法就是把它拖到 elevation gadget上。

1
Advertisement
1
1
2015-07-16 17:57:01 +0000
Advertisement

PowerShell ISE的位置在%windir%WindowsPowerShellv1.0中。你可以右键点击它,选择 “以管理员身份运行",然后在里面运行脚本。

0
0
0
2019-07-15 04:56:44 +0000

如果你想要一个选项,直接从资源管理器的上下文菜单中启动Powershell脚本作为管理员,请看我在这里的第二部分的回答。https://stackoverflow.com/a/57033941/2441655

-1
Advertisement
-1
-1
2017-10-23 20:34:16 +0000
Advertisement

在脚本的开头加上这句话:

$currentUser = New-Object Security.Principal.WindowsPrincipal $([Security.Principal.WindowsIdentity]::GetCurrent())
$testadmin = $currentUser.IsInRole([Security.Principal.WindowsBuiltinRole]::Administrator)
if ($testadmin -eq $false) {
Start-Process powershell.exe -Verb RunAs -ArgumentList ('-noprofile -noexit -file "{0}" -elevated' -f ($myinvocation.MyCommand.Definition))
exit $LASTEXITCODE
}
Advertisement

相关问题

3
28
13
7
9
Advertisement
Advertisement