您知道如果您是系统的管理员用户,您可以右键单击一个批处理脚本,然后以管理员身份运行它,而无需输入管理员密码?

我想知道如何用PowerShell脚本做到这一点。我不想输入我的密码;我只是想模仿右键单击Run As Administrator方法。

到目前为止,我读到的所有内容都要求您提供管理员密码。


当前回答

乔纳森和谢伊·列维发布的代码对我不起作用。

请在下面找到工作代码:

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应用程序创建应用程序包时自动生成。

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
}

C:\Users\“username”\AppData\漫游\Microsoft\Windows\开始菜单\程序\Windows PowerShell是PowerShell快捷方式所在的位置。它仍然会转到不同的位置来调用实际的“exe”(%SystemRoot%\system32\WindowsPowerShell\v1.0\powershell.exe)。

由于PowerShell在涉及权限时是用户配置文件驱动的;如果你的用户名/配置文件有权限做一些事情,那么在PowerShell中,你通常也可以这样做。也就是说,您可以更改位于用户配置文件下的快捷方式,例如C:\Users\"username"\AppData\Roaming\Microsoft\Windows\开始菜单\Programs\Windows PowerShell。

右键单击属性。点击“快捷方式”标签下的“高级”按钮,该标签位于“评论”文本框的右下方,与“打开文件位置”和“更改图标”两个按钮的右侧相邻。

选中“以管理员身份运行”的复选框。单击确定,然后应用和确定。再次右键单击位于C:\Users\“username”\AppData\漫游\Microsoft\Windows\开始菜单\程序\Windows PowerShell的图标,并选择“固定到开始菜单/任务栏”。

现在,无论何时单击该图标,它都会调用UAC进行升级。选择“YES”后,您将注意到PowerShell控制台打开,屏幕顶部将标记为“Administrator”。

更进一步说……你可以在Windows PowerShell的配置文件中右键单击相同的图标快捷方式,并分配一个键盘快捷方式,该快捷方式将执行与单击最近添加的图标完全相同的操作。所以在说“快捷键”的地方,输入键盘键/按钮组合,如:Ctrl + Alt + PP(适用于PowerShell)。单击“应用”和“确定”。

现在你所要做的就是按下你分配的按钮组合,你会看到UAC被调用,在你选择'YES'后,你会看到一个PowerShell控制台出现,“Administrator”显示在标题栏上。

我正在使用下面的解决方案。它通过转录特性处理stdout/stderr,并将退出码正确地传递给父进程。您需要调整文本路径/文件名。

If (-NOT ([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator"))
{ 
  echo "* Respawning PowerShell child process with elevated privileges"
  $pinfo = New-Object System.Diagnostics.ProcessStartInfo
  $pinfo.FileName = "powershell"
  $pinfo.Arguments = "& '" + $myinvocation.mycommand.definition + "'"
  $pinfo.Verb = "RunAs"
  $pinfo.RedirectStandardError = $false
  $pinfo.RedirectStandardOutput = $false
  $pinfo.UseShellExecute = $true
  $p = New-Object System.Diagnostics.Process
  $p.StartInfo = $pinfo
  $p.Start() | Out-Null
  $p.WaitForExit()
  echo "* Child process finished"
  type "C:/jenkins/transcript.txt"
  Remove-Item "C:/jenkins/transcript.txt"
  Exit $p.ExitCode
} Else {
  echo "Child process starting with admin privileges"
  Start-Transcript -Path "C:/jenkins/transcript.txt"
}

# Rest of your script goes here, it will be executed with elevated privileges

使用

#需要-RunAsAdministrator

还没有声明。它似乎是从PowerShell 4.0开始出现的。

http://technet.microsoft.com/en-us/library/hh847765.aspx

当这个switch参数被添加到require语句时, 它指定您所在的Windows PowerShell会话 运行脚本时必须使用提升的用户权限 (以管理员身份运行)。

对我来说,这似乎是一个很好的方法,但我还不确定现场经验。PowerShell 3.0运行时可能会忽略这一点,甚至更糟,会给出一个错误。

当脚本以非管理员身份运行时,会给出以下错误:

脚本“StackOverflow.”Ps1 '不能运行,因为它包含 以管理员身份运行的“#requires”语句。当前的 Windows PowerShell会话没有以管理员身份运行。开始 Windows PowerShell使用“以管理员身份运行”选项,然后 尝试再次运行脚本。 + CategoryInfo: PermissionDenied:(StackOverflow.ps1:String) [], ParentContainsErrorRecordException + fullyqualifiederrid: ScriptRequiresElevation