你知道如果您是系统的管理员用户,您可以右键点击批处理脚本并作为管理员运行而无需输入管理员密码吗?
我想知道如何在PowerShell脚本中实现这一点。 我不想输入密码; 我只想模拟右键单击“以管理员身份运行”的方法。
到目前为止,我阅读的所有内容都需要提供管理员密码。
你知道如果您是系统的管理员用户,您可以右键点击批处理脚本并作为管理员运行而无需输入管理员密码吗?
我想知道如何在PowerShell脚本中实现这一点。 我不想输入密码; 我只想模拟右键单击“以管理员身份运行”的方法。
到目前为止,我阅读的所有内容都需要提供管理员密码。
如果当前控制台没有提升权限,而你尝试的操作需要提升权限,则可以使用“以管理员身份运行”选项启动powershell
:
PS> Start-Process powershell -Verb runAs
CMD
窗口内部来看,最短的版本是:powershell start cmd -v runas
。要验证新获取的特权,请运行:net sess
。 - 303Start-Process wt -Verb runAs
以管理员身份启动Windows终端。 - Phillip Schulze这里是对Shay Levi建议的补充(只需在脚本开头添加这些行):
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
Break
}
这将导致当前的脚本被传递到一个新的以管理员身份运行的PowerShell进程中(如果当前用户有访问管理员权限的能力,并且该脚本没有以管理员身份运行)。
if
语句放入then
块中并添加一个throw
即可。 - jpmc26if (!([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator")) { Start-Process powershell.exe "-NoProfile -ExecutionPolicy Bypass -File `"$PSCommandPath`"" -Verb RunAs; exit }
# Your script here
if (!([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator")) { Start-Process powershell.exe "-NoProfile -ExecutionPolicy Bypass -File \
"$PSCommandPath`" `"$args`"" -Verb RunAs; exit }`。 - ab.Benjamin Armstrong发布了一篇关于自我提升的PowerShell脚本的优秀文章。他的代码有一些小问题;以下是基于评论中建议的修复的修改版本。
基本上,它获取与当前进程相关联的标识符,检查它是否为管理员,如果不是,则创建一个具有管理员特权的新PowerShell进程并终止旧进程。
# Get the ID and security principal of the current user account
$myWindowsID = [System.Security.Principal.WindowsIdentity]::GetCurrent();
$myWindowsPrincipal = New-Object System.Security.Principal.WindowsPrincipal($myWindowsID);
# Get the security principal for the administrator role
$adminRole = [System.Security.Principal.WindowsBuiltInRole]::Administrator;
# Check to see if we are currently running as an administrator
if ($myWindowsPrincipal.IsInRole($adminRole))
{
# We are running as an administrator, so change the title and background colour to indicate this
$Host.UI.RawUI.WindowTitle = $myInvocation.MyCommand.Definition + "(Elevated)";
$Host.UI.RawUI.BackgroundColor = "DarkBlue";
Clear-Host;
}
else {
# We are not running as an administrator, so relaunch as administrator
# Create a new process object that starts PowerShell
$newProcess = New-Object System.Diagnostics.ProcessStartInfo "PowerShell";
# Specify the current script path and name as a parameter with added scope and support for scripts with spaces in it's path
$newProcess.Arguments = "& '" + $script:MyInvocation.MyCommand.Path + "'"
# Indicate that the process should be elevated
$newProcess.Verb = "runas";
# Start the new process
[System.Diagnostics.Process]::Start($newProcess);
# Exit from the current, unelevated, process
Exit;
}
# Run your code that needs to be elevated here...
Write-Host -NoNewLine "Press any key to continue...";
$null = $Host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown");
这是一个用于 Powershell 脚本的自升级代码片段,它可以保留工作目录:
if (!([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)) {
Start-Process PowerShell -Verb RunAs "-NoProfile -ExecutionPolicy Bypass -Command `"cd '$pwd'; & '$PSCommandPath';`"";
exit;
}
# Your script here
对于执行路径相对操作的脚本而言,保留工作目录非常重要。几乎所有其他答案都没有保留此路径,这可能会导致脚本的其余部分出现意外错误。
如果您不想使用自我提升的脚本/代码段,而只是想以管理员身份轻松启动脚本(例如,从资源管理器上下文菜单中),请参阅我的其他回答:https://dev59.com/aKLia4cB1Zd3GeqPfTNj#57033941
您可以创建一个批处理文件(*.bat),通过双击运行它来以管理员特权运行您的PowerShell脚本。这样,您不需要更改您的PowerShell脚本中的任何内容。要实现此功能,请创建一个与您的PowerShell脚本具有相同名称和位置的批处理文件,然后将以下内容放入其中:
@echo off
set scriptFileName=%~n0
set scriptFolderPath=%~dp0
set powershellScriptFileName=%scriptFileName%.ps1
powershell -Command "Start-Process powershell \"-ExecutionPolicy Bypass -NoProfile -NoExit -Command `\"cd \`\"%scriptFolderPath%`\"; & \`\".\%powershellScriptFileName%\`\"`\"\" -Verb RunAs"
就是这样!
以下是解释:
假设你的PowerShell脚本位于路径C:\Temp\ScriptTest.ps1,则批处理文件必须具有路径C:\Temp\ScriptTest.bat。 当有人执行此批处理文件时,将发生以下步骤:
命令提示符将执行该命令:
powershell -Command "Start-Process powershell \"-ExecutionPolicy Bypass -NoProfile -NoExit -Command `\"cd \`\"C:\Temp\`\"; & \`\".\ScriptTest.ps1\`\"`\"\" -Verb RunAs"
一个新的 PowerShell 会话将被打开并执行以下命令: Start-Process powershell "-ExecutionPolicy Bypass -NoProfile -NoExit -Command `"cd \`"C:\Temp\`"; & \`".\ScriptTest.ps1\`"`"" -Verb RunAs
将以管理员权限在system32文件夹中打开另一个新的powershell会话,并传递以下参数:
-ExecutionPolicy Bypass -NoProfile -NoExit -Command "cd \"C:\Temp\"; & \".\ScriptTest.ps1\""
下面的命令将以管理员权限执行:cd "C:\Temp"; & ".\ScriptTest.ps1"
一旦脚本路径和名称参数用双引号括起来,它们可以包含空格或单引号字符(')。
当前文件夹将从system32更改为C:\Temp,并且将执行脚本ScriptTest.ps1
。 一旦传递了参数-NoExit
,即使您的powershell脚本引发了异常,窗口也不会关闭。
使用#Requires -RunAsAdministrator
命令是自PowerShell 4.0版本才开始提供的。此命令用于指定在运行脚本时,必须以管理员权限启动Windows PowerShell会话。详情请参阅http://technet.microsoft.com/en-us/library/hh847765.aspx。
尽管这似乎是解决问题的好方法,但我还不确定是否有实际应用经验。如果脚本在非管理员模式下运行,则会出现以下错误:
The script 'StackOverflow.ps1' cannot be run because it contains a "#requires" statement for running as Administrator. The current Windows PowerShell session is not running as Administrator. Start Windows PowerShell by using the Run as Administrator option, and then try running the script again.
另外,PowerShell 3.0运行时可能会忽略此命令,甚至会导致错误。
+ CategoryInfo : PermissionDenied: (StackOverflow.ps1:String) [], ParentContainsErrorRecordException
+ FullyQualifiedErrorId : ScriptRequiresElevation
您可以轻松地添加一些注册表条目,以获得.ps1
文件的“以管理员身份运行”上下文菜单:
您可以通过编辑注册表来为.ps1文件添加“以管理员身份运行”上下文菜单。
New-Item -Path "Registry::HKEY_CLASSES_ROOT\Microsoft.PowershellScript.1\Shell\runas\command" `
-Force -Name '' -Value '"c:\windows\system32\windowspowershell\v1.0\powershell.exe" -noexit "%1"'
(从@Shay那里更新了一个更简单的脚本)
基本上,在 HKCR:\Microsoft.PowershellScript.1\Shell\runas\command
处将默认值设置为使用 Powershell 调用脚本。
"c:\windows\system32\windowspowershell\v1.0\powershell.exe" -noexit -command "& '%1'"
。 - Kal ZekdorJonathan和Shay Levy发布的代码对我无效。
请找到下面的有效代码:
If (-NOT ([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator"))
{
#"No Administrative rights, it will display a popup window asking user for Admin rights"
$arguments = "& '" + $myinvocation.mycommand.definition + "'"
Start-Process "$psHome\powershell.exe" -Verb runAs -ArgumentList $arguments
break
}
#"After user clicked Yes on the popup, your file will be reopened with Admin rights"
#"Put your code here"
请以管理员权限重新运行脚本,并检查脚本是否在此模式下启动。下面我编写了一个包含两个函数的脚本:DoElevatedOperations和DoStandardOperations。您应该将需要管理员权限的代码放入第一个函数中,将标准操作放入第二个函数中。变量IsRunAsAdmin用于识别管理员模式。
我的代码是从创建Windows Store应用程序包时自动生成的Microsoft脚本中提取的简化版本。
param(
[switch]$IsRunAsAdmin = $false
)
# Get our script path
$ScriptPath = (Get-Variable MyInvocation).Value.MyCommand.Path
#
# Launches an elevated process running the current script to perform tasks
# that require administrative privileges. This function waits until the
# elevated process terminates.
#
function LaunchElevated
{
# Set up command line arguments to the elevated process
$RelaunchArgs = '-ExecutionPolicy Unrestricted -file "' + $ScriptPath + '" -IsRunAsAdmin'
# Launch the process and wait for it to finish
try
{
$AdminProcess = Start-Process "$PsHome\PowerShell.exe" -Verb RunAs -ArgumentList $RelaunchArgs -PassThru
}
catch
{
$Error[0] # Dump details about the last error
exit 1
}
# Wait until the elevated process terminates
while (!($AdminProcess.HasExited))
{
Start-Sleep -Seconds 2
}
}
function DoElevatedOperations
{
Write-Host "Do elevated operations"
}
function DoStandardOperations
{
Write-Host "Do standard operations"
LaunchElevated
}
#
# Main script entry point
#
if ($IsRunAsAdmin)
{
DoElevatedOperations
}
else
{
DoStandardOperations
}
gsudo
。它是Windows的一个免费开源sudo工具,允许从命令行以管理员身份执行操作。会出现UAC弹窗。 - Gerardo Grignoli