使用PowerShell以管理员身份运行命令?

使用PowerShell以管理员身份运行命令?,powershell,administrator,Powershell,Administrator,您知道如果您是系统的管理用户,只需右键单击批处理脚本并以管理员身份运行,而无需输入管理员密码 我想知道如何使用PowerShell脚本实现这一点。我不想输入我的密码;我只想模拟右键单击以管理员身份运行的方法 到目前为止,我阅读的所有内容都要求您提供管理员密码。此行为是出于设计。由于微软真的不希望.ps1文件成为最新的电子邮件病毒,因此存在多个安全层。有些人发现这与任务自动化的概念背道而驰,这是公平的。Vista+安全模式是“去自动化”的,这样用户就可以放心了 但是,我怀疑如果您将powershe

您知道如果您是系统的管理用户,只需右键单击批处理脚本并以管理员身份运行,而无需输入管理员密码

我想知道如何使用PowerShell脚本实现这一点。我不想输入我的密码;我只想模拟右键单击以管理员身份运行的方法


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

此行为是出于设计。由于微软真的不希望.ps1文件成为最新的电子邮件病毒,因此存在多个安全层。有些人发现这与任务自动化的概念背道而驰,这是公平的。Vista+安全模式是“去自动化”的,这样用户就可以放心了


但是,我怀疑如果您将powershell本身作为提升版启动,在关闭powershell之前,它应该能够在不再次请求密码的情况下运行批处理文件。

如果当前控制台未提升,并且您尝试执行的操作需要提升的权限,则您可以使用以管理员身份运行选项启动
powershell

PS> Start-Process powershell -Verb runAs

您可以轻松添加一些注册表项,以获得
.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调用脚本。

这里是对Shay Levi建议的补充(只需在脚本开头添加以下行):

if(-NOT([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole]“Administrator”))
{  
$arguments=“&”+$myinvocation.mycommand.definition+”“
启动进程powershell-动词运行方式-ArgumentList$参数
打破
}

这将导致当前脚本以管理员模式传递给新的powershell进程(如果当前用户可以访问管理员模式,并且脚本不是以管理员身份启动的)。

另一个更简单的解决方案是,您也可以右键单击“C:\Windows\System32\cmd.exe”并选择“以管理员身份运行”然后,您可以作为管理员运行任何应用程序,而无需提供任何密码。

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

请在下面查找工作代码:

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。您应该将需要管理员权限的代码放在第一个代码中,将标准操作放在第二个代码中。ISRUNAADMIN变量用于标识管理模式

“我的代码”是Microsoft脚本的简化摘录,该脚本在为Windows应用商店应用程序创建应用程序包时自动生成

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
}

在Shay Levy的答案之上,按照以下设置(仅一次)

  • 启动具有管理员权限的PowerShell
  • 下面是堆栈溢出问题
  • 例如,将.ps1文件放在任何
    路径
    文件夹中。Windows\System32文件夹
  • 安装后:

  • 按Win+R
  • 调用powershell启动进程powershell-动词runAs
  • 现在,您可以在一个命令行中运行所有内容。以上内容适用于Windows8基本64位。

    使用

    #需要-运行管理员

    尚未说明。它似乎是在PowerShell 4.0之后才出现的

    将此开关参数添加到requires语句时, 它指定您所在的Windows PowerShell会话 必须以提升的用户权限开始运行脚本 (以管理员身份运行)

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

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

    无法运行脚本“StackOverflow.ps1”,因为它包含 以管理员身份运行的“#requires”语句。电流 Windows PowerShell会话未以管理员身份运行。开始 通过使用“以管理员身份运行”选项运行Windows PowerShell,然后 请尝试再次运行脚本

    + CategoryInfo          : PermissionDenied: (StackOverflow.ps1:String) [], ParentContainsErrorRecordException
    + FullyQualifiedErrorId : ScriptRequiresElevation
    

    本杰明·阿姆斯特朗发表了一份声明。他的代码有一些小问题;下面是基于评论中建议的修复的修改版本

    基本上,它获取与当前进程相关联的标识,检查它是否是管理员,如果不是,则创建具有管理员权限的新PowerShell进程并终止旧进程

    #获取当前用户帐户的ID和安全主体
    $myWindowsID=[System.Security.Principal.WindowsIdentity]::GetCurrent();
    $myWindowsPrincipal=新对象System.Security.Principal.WindowsPrincipal($myWindowsID);
    #获取管理员角色的安全主体
    $adminRole=[System.Security.Principal.WindowsBuiltInRole]::管理员;
    #检查我们当前是否以管理员身份运行
    if($myWindowsPrincipal.IsInRole($adminRole))
    {
    #我们是以管理员身份运行的,因此请更改标题和背景颜色以表明这一点
    $Host.UI.RawUI.WindowTitle=$myInvocation.MyCommand.Definition+“(提升)”;
    $Host.UI.RawUI.BackgroundColor=“暗蓝色”;
    明确宿主;
    }
    否则{
    #我们不是以管理员身份运行,请以管理员身份重新启动
    #创建启动PowerShell的新流程对象
    $newProcess=新对象System.Diagnostics.ProcessStartInfo“PowerShell”;
    #将当前脚本路径和名称指定为参数,并为路径中带有空格的脚本添加范围和支持
    $newProcess.Arguments=“&”+
    
    @echo off
    START "" "C:\Scripts\ScriptName.ps1"
    
    C:\Windows\System32\runas.exe /savecred /user:*DOMAIN*\*ADMIN USERNAME* C:\Scripts\BatchFileName.bat
    
    if (!([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([bool]([Security.Principal.WindowsIdentity]::GetCurrent()).Groups -notcontains "S-1-5-32-544") {
        Start Powershell -ArgumentList "& '$MyInvocation.MyCommand.Path'" -Verb runas
        }
    
    $winupdfile = 'Windows-Update-' + $(get-date -f MM-dd-yyyy) + '.txt'
    if (!([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator")) { Start-Process powershell.exe "-NoProfile -ExecutionPolicy Bypass -Command `"Get-WUInstall -AcceptAll | Out-File $env:USERPROFILE\$winupdfile -Append`"" -Verb RunAs; exit } else { Start-Process powershell.exe "-NoProfile -ExecutionPolicy Bypass -Command `"Get-WUInstall -AcceptAll | Out-File $env:USERPROFILE\$winupdfile -Append`""; exit }
    
    @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 -Command "Start-Process powershell \"-ExecutionPolicy Bypass -NoProfile -NoExit -Command `\"cd \`\"C:\Temp\`\"; & \`\".\ScriptTest.ps1\`\"`\"\" -Verb RunAs"
    
    Start-Process powershell "-ExecutionPolicy Bypass -NoProfile -NoExit -Command `"cd \`"C:\Temp\`"; & \`".\ScriptTest.ps1\`"`"" -Verb RunAs
    
    -ExecutionPolicy Bypass -NoProfile -NoExit -Command "cd \"C:\Temp\"; & \".\ScriptTest.ps1\""
    
    cd "C:\Temp"; & ".\ScriptTest.ps1"
    
    @echo off
    NET SESSION 1>NUL 2>NUL
    IF %ERRORLEVEL% EQU 0 GOTO ADMINTASKS
    CD %~dp0
    MSHTA "javascript: var shell = new ActiveXObject('shell.application'); shell.ShellExecute('%~nx0', '', '', 'runas', 0); close();"
    EXIT
    
    :ADMINTASKS
    
    powershell -file "c:\users\joecoder\scripts\admin_tasks.ps1"
    
    EXIT
    
    [CmdletBinding(DefaultParametersetName='RunWithPowerShellContextMenu')]
    param (
        [parameter(ParameterSetName='CallFromCommandLine')]
        [switch] $CallFromCommandLine,
    
        [parameter(Mandatory=$false, ParameterSetName='RunWithPowerShellContextMenu')]
        [parameter(Mandatory=$true, ParameterSetName='CallFromCommandLine')]
        [string] $ComputerName,
    
        [parameter(Mandatory=$false, ParameterSetName='RunWithPowerShellContextMenu')]
        [parameter(Mandatory=$true, ParameterSetName='CallFromCommandLine')]
        [UInt16] $Port
    )
    
    function Assert-AdministrativePrivileges([bool] $CalledFromRunWithPowerShellMenu)
    {
        $isAdministrator = ([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)
    
        if ($isAdministrator)
        {
            if (!$CalledFromRunWithPowerShellMenu -and !$CallFromCommandLine)
            {
                # Must call itself asking for obligatory parameters
                & "$PSCommandPath" @script:PSBoundParameters -CallFromCommandLine
                Exit
            }
        }
        else
        {
            if (!$CalledFromRunWithPowerShellMenu -and !$CallFromCommandLine)
            {
                $serializedParams = [Management.Automation.PSSerializer]::Serialize($script:PSBoundParameters)
    
                $scriptStr = @"
                    `$serializedParams = '$($serializedParams -replace "'", "''")'
    
                    `$params = [Management.Automation.PSSerializer]::Deserialize(`$serializedParams)
    
                    & "$PSCommandPath" @params -CallFromCommandLine
    "@
    
                $scriptBytes = [System.Text.Encoding]::Unicode.GetBytes($scriptStr)
                $encodedCommand = [Convert]::ToBase64String($scriptBytes)
    
                # If this script is called from another one, the execution flow must wait for this script to finish.
                Start-Process -FilePath 'powershell' -ArgumentList "-ExecutionPolicy Bypass -NoProfile -EncodedCommand $encodedCommand" -Verb 'RunAs' -Wait
            }
            else
            {
                # When you use the "Run with PowerShell" feature, the Windows PowerShell console window appears only briefly.
                # The NoExit option makes the window stay visible, so the user can see the script result.
                Start-Process -FilePath 'powershell' -ArgumentList "-ExecutionPolicy Bypass -NoProfile -NoExit -File ""$PSCommandPath""" -Verb 'RunAs'
            }
    
            Exit
        }
    }
    
    function Get-UserParameters()
    {
        [string] $script:ComputerName = [Microsoft.VisualBasic.Interaction]::InputBox('Enter a computer name:', 'Testing Network Connection')
    
        if ($script:ComputerName -eq '')
        {
            throw 'The computer name is required.'
        }
    
        [string] $inputPort = [Microsoft.VisualBasic.Interaction]::InputBox('Enter a TCP port:', 'Testing Network Connection')
    
        if ($inputPort -ne '')
        {
            if (-not [UInt16]::TryParse($inputPort, [ref]$script:Port))
            {
                throw "The value '$inputPort' is invalid for a port number."
            }
        }
        else
        {
            throw 'The TCP port is required.'
        }
    }
    
    # $MyInvocation.Line is empty in the second script execution, when a new powershell session
    # is started for this script via Start-Process with the -File option.
    $calledFromRunWithPowerShellMenu = $MyInvocation.Line -eq '' -or $MyInvocation.Line.StartsWith('if((Get-ExecutionPolicy')
    
    Assert-AdministrativePrivileges $calledFromRunWithPowerShellMenu
    
    # Necessary for InputBox
    [System.Reflection.Assembly]::Load('Microsoft.VisualBasic, Version=10.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a') | Out-Null
    
    if ($calledFromRunWithPowerShellMenu)
    {
        Get-UserParameters
    }
    
    # ... script code
    Test-NetConnection -ComputerName $ComputerName -Port $Port
    
    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
    
    if (!(net session)) {$path =  "& '" + $myinvocation.mycommand.definition + "'" ; Start-Process powershell -Verb runAs -ArgumentList $path ; exit}
    
    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
    
    powershell -Command 'Start-Process powershell -ArgumentList "-Command (Get-Process postgres | Select-Object Path | Select-Object -Index 0).Path | Out-File -encoding ASCII $env:TEMP\camp-postgres.tmp" -Verb RunAs'