Saj*_*jee 88 windows-7 powershell
在我的 Windows 7 桌面上,我有 script.ps1,它需要管理员权限(它启动一个服务)。我想单击此脚本并以管理员权限运行它。
实现这一目标的最简单方法是什么?
Kez*_*Kez 67
借助桌面上的附加图标,这是一种方法。如果您只想在桌面上有一个图标,我想您可以将脚本移至其他人。
您现在可以通过简单地双击桌面上的新快捷方式来运行提升的脚本。
MDM*_*313 33
在启用 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'
Run Code Online (Sandbox Code Playgroud)
现在,当运行您的脚本时,它会再次调用自己并尝试在运行前提升权限。-elevated 开关防止它在出现故障时重复。
-noexit如果脚本完成后终端应自动关闭,您可以删除开关。
mjs*_*jsr 16
如果你在同一个 powershell 中,你可以这样做:
Start-Process powershell -verb runas -ArgumentList "-file fullpathofthescript"
Run Code Online (Sandbox Code Playgroud)
小智 5
除了上面 MDMoore313 的回答之外:
如果我们想在当前所在的同一工作目录中执行命令,我们必须添加一些内容:
#### START ELEVATE TO ADMIN #####
param(
[Parameter(Mandatory=$false)]
[switch]$shouldAssumeToBeElevated,
[Parameter(Mandatory=$false)]
[String]$workingDirOverride
)
# If parameter is not set, we are propably in non-admin execution. We set it to the current working directory so that
# the working directory of the elevated execution of this script is the current working directory
if(-not($PSBoundParameters.ContainsKey('workingDirOverride')))
{
$workingDirOverride = (Get-Location).Path
}
function Test-Admin {
$currentUser = New-Object Security.Principal.WindowsPrincipal $([Security.Principal.WindowsIdentity]::GetCurrent())
$currentUser.IsInRole([Security.Principal.WindowsBuiltinRole]::Administrator)
}
# If we are in a non-admin execution. Execute this script as admin
if ((Test-Admin) -eq $false) {
if ($shouldAssumeToBeElevated) {
Write-Output "Elevating did not work :("
} else {
# vvvvv add `-noexit` here for better debugging vvvvv
Start-Process powershell.exe -Verb RunAs -ArgumentList ('-noprofile -file "{0}" -shouldAssumeToBeElevated -workingDirOverride "{1}"' -f ($myinvocation.MyCommand.Definition, "$workingDirOverride"))
}
exit
}
Set-Location "$workingDirOverride"
##### END ELEVATE TO ADMIN #####
# Add actual commands to be executed in elevated mode here:
Write-Output "I get executed in an admin PowerShell"
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
338207 次 |
| 最近记录: |