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

发布于 2024-12-08 20:34:10 字数 170 浏览 2 评论 0原文

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

我想知道如何使用 PowerShell 脚本来执行此操作。我不想输入密码;我只是想模仿右键单击以管理员身份运行方法。

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

You know how if you're the administrative user of a system and you can just right click say, a batch script and run it as Administrator without entering the administrator password?

I'm wondering how to do this with a PowerShell script. I do not want to have to enter my password; I just want to mimic the right-click Run As Administrator method.

Everything I read so far requires you to supply the administrator password.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(30

不气馁 2024-12-15 20:34:10

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

PS> Start-Process powershell -Verb runAs

Microsoft 文档:启动进程

If the current console is not elevated and the operation you're trying to do requires elevated privileges then you can start powershell with the Run as Administrator option :

PS> Start-Process powershell -Verb runAs

Microsoft Docs: Start-Process

糖果控 2024-12-15 20:34:10

这是 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 进程(如果当前用户有权访问管理员模式并且脚本是未以管理员身份启动)。

Here is an addition to Shay Levi's suggestion (just add these lines at the beginning of a script):

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
}

This results in the current script being passed to a new powershell process in Administrator mode (if current User has access to Administrator mode and the script is not launched as Administrator).

英雄似剑 2024-12-15 20:34:10

自提升 PowerShell 脚本

Windows 8.1 / PowerShell 4.0 +

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

Self elevating PowerShell script

Windows 8.1 / PowerShell 4.0 +

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
伴我心暖 2024-12-15 20:34:10

本杰明·阿姆斯特朗 (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");

Benjamin Armstrong posted an excellent article about self-elevating PowerShell scripts. There a few minor issue with his code; a modified version based on fixes suggested in the comment is below.

Basically it gets the identity associated with the current process, checks whether it is an administrator, and if it isn't, creates a new PowerShell process with administrator privileges and terminates the old process.

# 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");
淡墨 2024-12-15 20:34:10

以下是 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://stackoverflow.com/a/57033941/2441655

Here's a self-elevating snippet for Powershell scripts which preserves the working directory:

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

Preserving the working directory is important for scripts that perform path-relative operations. Almost all of the other answers do not preserve this path, which can cause unexpected errors in the rest of the script.

If you'd rather not use a self-elevating script/snippet, and instead just want an easy way to launch a script as adminstrator (eg. from the Explorer context-menu), see my other answer here: https://stackoverflow.com/a/57033941/2441655

吃素的狼 2024-12-15 20:34:10

您可以创建一个批处理文件 (*.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 >。当有人执行这个批处理文件时,会发生以下步骤:

  1. cmd将执行命令

    powershell -Command "Start-Process powershell \"-ExecutionPolicy Bypass -NoProfile -NoExit -Command `\"cd \`\"C:\Temp\`\"; & \`\".\ ScriptTest.ps1\`\"`\"\" -Verb RunAs"
    
  2. 将打开一个新的 powershell 会话并执行以下命令:

    启动进程 powershell "-ExecutionPolicy Bypass -NoProfile -NoExit -Command `"cd \`"C:\Temp\`"; & \`".\ScriptTest.ps1\`"`"" -Verb RunAs
    
  3. 将在 system32 文件夹中打开另一个具有管理权限的新 powershell 会话,并将以下参数传递给它:

    -ExecutionPolicy 绕过 -NoProfile -NoExit -Command "cd \"C:\Temp\"; & \".\ScriptTest.ps1\""
    
  4. 以下命令将以管理权限执行:

    cd "C:\Temp"; & “.\ScriptTest.ps1”
    

    一旦脚本路径和名称参数被双引号括起来,它们就可以包含空格或单引号字符 (')。

  5. 当前文件夹将从system32更改为C:\Temp,并且脚本ScriptTest.ps1将被执行。一旦传递了参数-NoExit,即使您的powershell脚本抛出一些异常,窗口也不会关闭。

You can create a batch file (*.bat) that runs your powershell script with administrative privileges when double-clicked. In this way, you do not need to change anything in your powershell script.To do this, create a batch file with the same name and location of your powershell script and then put the following content in it:

@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"

That's it!

Here is the explanation:

Assuming your powershell script is in the path C:\Temp\ScriptTest.ps1, your batch file must have the path C:\Temp\ScriptTest.bat. When someone execute this batch file, the following steps will occur:

  1. The cmd will execute the command

    powershell -Command "Start-Process powershell \"-ExecutionPolicy Bypass -NoProfile -NoExit -Command `\"cd \`\"C:\Temp\`\"; & \`\".\ScriptTest.ps1\`\"`\"\" -Verb RunAs"
    
  2. A new powershell session will open and the following command will be executed:

    Start-Process powershell "-ExecutionPolicy Bypass -NoProfile -NoExit -Command `"cd \`"C:\Temp\`"; & \`".\ScriptTest.ps1\`"`"" -Verb RunAs
    
  3. Another new powershell session with administrative privileges will open in the system32 folder and the following arguments will be passed to it:

    -ExecutionPolicy Bypass -NoProfile -NoExit -Command "cd \"C:\Temp\"; & \".\ScriptTest.ps1\""
    
  4. The following command will be executed with administrative privileges:

    cd "C:\Temp"; & ".\ScriptTest.ps1"
    

    Once the script path and name arguments are double quoted, they can contain space or single quotation mark characters (').

  5. The current folder will change from system32 to C:\Temp and the script ScriptTest.ps1 will be executed. Once the parameter -NoExit was passed, the window wont be closed, even if your powershell script throws some exception.

冷清清 2024-12-15 20:34:10

使用

#Requires -RunAsAdministrator

尚未说明 。它似乎是从 PowerShell 4.0 才出现的。

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

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

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

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

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

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

Using

#Requires -RunAsAdministrator

has not been stated, yet. It seems to be there only since PowerShell 4.0.

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

When this switch parameter is added to your requires statement,
it specifies that the Windows PowerShell session in which you are
running the script must be started with elevated user rights
(Run as Administrator).

To me, this seems like a good way to go about this, but I'm not sure of the field experience, yet. PowerShell 3.0 runtimes probably ignore this, or even worse, give an error.

When the script is run as a non-administrator, the following error is given:

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.

+ CategoryInfo          : PermissionDenied: (StackOverflow.ps1:String) [], ParentContainsErrorRecordException
+ FullyQualifiedErrorId : ScriptRequiresElevation
究竟谁懂我的在乎 2024-12-15 20:34:10

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

You can easily add some registry entries to get a "Run as administrator" context menu for .ps1 files:

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"'

(updated to a simpler script from @Shay)

Basically at HKCR:\Microsoft.PowershellScript.1\Shell\runas\command set the default value to invoke the script using Powershell.

下壹個目標 2024-12-15 20:34:10

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

请找到下面的工作代码:

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"

The code posted by Jonathan and Shay Levy did not work for me.

Please find the working code below:

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"
似最初 2024-12-15 20:34:10

您需要使用管理权限重新运行该脚本,并检查该脚本是否在该模式下启动。下面我编写了一个具有两个函数的脚本:DoElevatedOperationsDoStandardOperations。您应该将需要管理员权限的代码放入第一个,将标准操作放入第二个。 IsRunAsAdmin 变量用于标识管理模式。

我的代码是 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
}

You need to rerun the script with administrative privileges and check if the script was launched in that mode. Below I have written a script that has two functions: DoElevatedOperations and DoStandardOperations. You should place your code that requires admin rights into the first one and standard operations into the second. The IsRunAsAdmin variable is used to identify the admin mode.

My code is an simplified extract from the Microsoft script that is automatically generated when you create an app package for Windows Store apps.

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
}
ゃ懵逼小萝莉 2024-12-15 20:34:10

当然,如果您有管理员帐户,您还可以强制应用程序以管理员身份打开。

输入图片此处描述

找到该文件,右键单击 >属性>快捷方式>高级并选中以管理员身份运行

然后单击“确定”。

You can also force the application to open as administrator, if you have an administrator account, of course.

enter image description here

Locate the file, right click > properties > Shortcut > Advanced and check Run as Administrator

Then Click OK.

尴尬癌患者 2024-12-15 20:34:10

添加我的 2 美分。我的基于网络会话的简单版本到目前为止一直在 Windows 7 / Windows 10 中运行。为什么要让它变得复杂呢?

if (!(net session)) {$path =  "& '" + $myinvocation.mycommand.definition + "'" ; Start-Process powershell -Verb runAs -ArgumentList $path ; exit}

只需添加到脚本的顶部,它将以管理员身份运行。

Adding my 2 cents. My simple version based on net session which works all the time so far in Windows 7 / Windows 10. Why over complicate it?

if (!(net session)) {$path =  "& '" + $myinvocation.mycommand.definition + "'" ; Start-Process powershell -Verb runAs -ArgumentList $path ; exit}

just add to the top of the script and it will run as administrator.

若无相欠,怎会相见 2024-12-15 20:34:10

这里的许多答案都很接近,但比需要的工作多了一点。

创建脚本的快捷方式并将其配置为“以管理员身份运行”:

  • 创建快捷方式。
  • 右键单击快捷方式并打开 Properties...
  • Target 编辑为 powershell;
  • 单击高级... 并启用以管理员身份运行

A number of the answers here are close, but a little more work than needed.

Create a shortcut to your script and configure it to "Run as Administrator":

  • Create the shortcut.
  • Right-click shortcut and open Properties...
  • Edit Target from <script-path> to powershell <script-path>
  • Click Advanced... and enable Run as administrator
初见你 2024-12-15 20:34:10

此行为是设计使然。由于 Microsoft 确实不希望 .ps1 文件成为最新的电子邮件病毒,因此存在多层安全性。有些人发现这与任务自动化的概念背道而驰,这是公平的。 Vista+ 安全模型是“去自动化”事物,从而使用户同意它们。

但是,我怀疑如果您以提升的方式启动 powershell 本身,它应该能够运行批处理文件,而无需再次请求密码,直到您关闭 powershell。

This behavior is by design. There are multiple layers of security since Microsoft really didn't want .ps1 files to be the latest email virus. Some people find this to be counter to the very notion of task automation, which is fair. The Vista+ security model is to "de-automate" things, thus making the user okay them.

However, I suspect if you launch powershell itself as elevated, it should be able to run batch files without requesting the password again until you close powershell.

夏末的微笑 2024-12-15 20:34:10

以下是如何运行提升的 powershell 命令并在单个命令中收集 Windows 批处理文件中的输出形式(即不编写 ps1 powershell 脚本)。

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'

在上面您可以看到我首先使用提升的提示符启动一个 powershell,然后要求启动另一个 powershell(子 shell)来运行该命令。

Here is how to run a elevated powershell command and collect its output form within a windows batch file in a single command(i.e not writing a ps1 powershell script).

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'

Above you see i first launch a powershell with elevated prompt and then ask that to launch another powershell(sub shell) to run the command.

意犹 2024-12-15 20:34:10

C:\Users\"username"\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Windows PowerShell 是 PowerShell 的快捷方式所在的位置。它仍然会转到不同的位置来调用实际的“exe”(%SystemRoot%\system32\WindowsPowerShell\v1.0\powershell.exe)。

由于在涉及权限时 PowerShell 是由用户配置文件驱动的;如果您的用户名/个人资料有权执行某些操作,那么在该个人资料下,在 PowerShell 中您通常也可以执行此操作。话虽如此,您应该更改用户配置文件下的快捷方式,例如 C:\Users\"username"\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Windows PowerShell 。

右键单击并单击属性。单击“快捷方式”选项卡下的“高级”按钮,该按钮位于“注释”文本字段正下方,分别与其他两个按钮“打开文件位置”和“更改图标”右侧相邻。

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

现在,每当您单击该图标时,它都会调用 UAC 进行升级。选择“是”后,您将注意到 PowerShell 控制台打开,并且屏幕顶部将标记为“管理员”。

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

现在您所要做的就是按下您分配的按钮组合,您将看到 UAC 被调用,选择“是”后,您将看到出现一个 PowerShell 控制台并在标题栏上显示“管理员”。

C:\Users\"username"\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Windows PowerShell is where the shortcut of PowerShell resides. It too still goes to a different location to invoke the actual 'exe' (%SystemRoot%\system32\WindowsPowerShell\v1.0\powershell.exe).

Since PowerShell is user-profile driven when permissions are concerned; if your username/profile has the permissions to do something then under that profile, in PowerShell you would generally be able to do it as well. That being said, it would make sense that you would alter the shortcut located under your user profile, for example, C:\Users\"username"\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Windows PowerShell.

Right-click and click properties. Click "Advanced" button under the "Shortcut" tab located right below the "Comments" text field adjacent to the right of two other buttons, "Open File Location" and "Change Icon", respectively.

Check the checkbox that reads, "Run as Administrator". Click OK, then Apply and OK. Once again right click the icon labeled 'Windows PowerShell' located in C:\Users\"username"\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Windows PowerShell and select "Pin to Start Menu/Taskbar".

Now whenever you click that icon, it will invoke the UAC for escalation. After selecting 'YES', you will notice the PowerShell console open and it will be labeled "Administrator" on the top of the screen.

To go a step further... you could right click that same icon shortcut in your profile location of Windows PowerShell and assign a keyboard shortcut that will do the exact same thing as if you clicked the recently added icon. So where it says "Shortcut Key" put in a keyboard key/button combination like: Ctrl + Alt + PP (for PowerShell). Click Apply and OK.

Now all you have to do is press that button combination you assigned and you will see UAC get invoked, and after you select 'YES' you will see a PowerShell console appear and "Administrator" displayed on the title bar.

柠北森屋 2024-12-15 20:34:10

我找到了一种方法来做到这一点...

创建一个批处理文件来打开脚本:

@echo off
START "" "C:\Scripts\ScriptName.ps1"

然后在桌面上创建一个快捷方式(右键单击新建 -> 快捷方式)。

然后将其粘贴到以下位置:

C:\Windows\System32\runas.exe /savecred /user:*DOMAIN*\*ADMIN USERNAME* C:\Scripts\BatchFileName.bat

首次打开时,您必须输入一次密码。然后,这会将其保存在 Windows 凭据管理器中。

之后,您应该能够以管理员身份运行,而无需输入管理员用户名或密码。

I have found a way to do this...

Create a batch file to open your script:

@echo off
START "" "C:\Scripts\ScriptName.ps1"

Then create a shortcut, on your desktop say (right click New -> Shortcut).

Then paste this into the location:

C:\Windows\System32\runas.exe /savecred /user:*DOMAIN*\*ADMIN USERNAME* C:\Scripts\BatchFileName.bat

When first opening, you will have to enter your password once. This will then save it in the Windows credential manager.

After this you should then be able to run as administrator without having to enter a administrator username or password.

风流物 2024-12-15 20:34:10

我正在使用下面的解决方案。它通过转录功能处理 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

I am using the solution below. It handles stdout/stderr via transcript feature and passes exit code correctly to parent process. You need to adjust transcript path/filename.

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
ˇ宁静的妩媚 2024-12-15 20:34:10

@pgk@Andrew Odri 的答案是当你有脚本参数时,特别是当它们是强制性的时。您可以使用以下方法解决此问题:

  1. 用户右键单击.ps1文件并选择“使用PowerShell运行”:通过输入框向他询问参数(这是一个比使用 HelpMessage 参数属性);
  2. 用户通过控制台执行脚本:允许他传递所需的参数,并让控制台强制他告知强制的参数。

如果脚本具有 ComputerNamePort 强制参数,则代码如下:

[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

The problem with the @pgk and @Andrew Odri's answers is when you have script parameters, specially when they are mandatory. You can solve this problem using the following approach:

  1. The user right-clicks the .ps1 file and selects 'Run with PowerShell': ask him for the parameters through input boxes (this is a much better option than use the HelpMessage parameter attribute);
  2. The user executes the script through the console: allow him to pass the desired parameters and let the console force him to inform the mandatory ones.

Here is how would be the code if the script had the ComputerName and Port mandatory parameters:

[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
酷到爆炸 2024-12-15 20:34:10

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

Another simpler solution is that you may also right click on "C:\Windows\System32\cmd.exe" and choose "Run as Administrator" then you can run any app as administrator without providing any password.

海风掠过北极光 2024-12-15 20:34:10

我最近需要这个来在ansible上构建一个环境。我马上说——决定不是我的,但我不记得我从哪里得到的。看起来像这样:

powershell.exe -NoProfile -ExecutionPolicy Unrestricted -Command "& {Start-Process PowerShell -ArgumentList '-NoProfile -ExecutionPolicy Unrestricted -Command Get-Service -Name ssh-agent | Set-Service -StartupType Automatic' -Verb RunAs}";

此示例启用 ssh-agent 自动启动。
所需的命令在-Command 之后指定。唯一的问题是启动发生在新的 PS 实例上,但到目前为止,这是我知道以管理员身份执行命令而无需执行其他步骤的唯一方法。

I recently needed this to build an environment on ansible. I say right away - the decision is not mine, but I don’t remember where I got it. Looks like that:

powershell.exe -NoProfile -ExecutionPolicy Unrestricted -Command "& {Start-Process PowerShell -ArgumentList '-NoProfile -ExecutionPolicy Unrestricted -Command Get-Service -Name ssh-agent | Set-Service -StartupType Automatic' -Verb RunAs}";

This example enables ssh-agent autostart.
The required command is specified after -Command. The only problem is the launch happens on a new PS instance, but so far this is the only way that I know to execute the command as an admin without additional steps.

不乱于心 2024-12-15 20:34:10

现有答案缺乏参数和工作目录直通。

这是我的片段:

if (!([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator")) {
    Write-Host "Running as non-administrator, restarting as administrator..."
    $powershell = if($PSVersionTable.PSVersion.Major -gt 5) { "pwsh.exe" } else { "powershell.exe" }
    $arguments = ($PsBoundParameters.GetEnumerator() | ForEach-Object { "-$($_.Key) `"$($_.Value)`"" }) -join " "
    Start-Process $powershell  -WorkingDirectory (Get-Location) -Verb RunAs -Wait "-NoProfile -ExecutionPolicy Bypass -File `"$PSCommandPath`" $arguments"; exit 
} 

Existing answers lacked arguments and working directory passthrough.

Here is my snippet:

if (!([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator")) {
    Write-Host "Running as non-administrator, restarting as administrator..."
    $powershell = if($PSVersionTable.PSVersion.Major -gt 5) { "pwsh.exe" } else { "powershell.exe" }
    $arguments = ($PsBoundParameters.GetEnumerator() | ForEach-Object { "-$($_.Key) `"$($_.Value)`"" }) -join " "
    Start-Process $powershell  -WorkingDirectory (Get-Location) -Verb RunAs -Wait "-NoProfile -ExecutionPolicy Bypass -File `"$PSCommandPath`" $arguments"; exit 
} 
香草可樂 2024-12-15 20:34:10

我发现的最可靠的方法是将其包装在自提升的 .bat 文件中:

@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

.bat 检查您是否已经是管理员,并在需要时以管理员身份重新启动脚本。它还可以防止将 ShellExecute() 的第四个参数设置为 0 时打开无关的“cmd”窗口。

The most reliable way I've found is to wrap it in a self-elevating .bat file:

@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

The .bat checks if you're already admin and relaunches the script as Administrator if needed. It also prevents extraneous "cmd" windows from opening with the 4th parameter of ShellExecute() set to 0.

水溶 2024-12-15 20:34:10

2024 年,如果您运行的是 Windows 11 Insider Preview Build 26052 或更高版本,Windows 会发布应用程序 Windows 版 Sudo (sudo.exe) 其工作方式与 Unix 的 Sudo 类似。

  • CLI CMD
sudo.exe cmd.exe
sudo.exe cmd.exe /c "path to batch file"
sudo.exe bcdedit.exe /enum bootmgr
  • CLI PowerShell
sudo.exe powershell.exe
sudo.exe powershell.exe -file "path to ps1 file"
sudo.exe bcdedit.exe /enum bootmgr
  • FILE
sudo.exe cmd.exe /c "%~0"
sudo.exe powershell.exe -file "$PSCommandPath"

命令行中的更多选项 sudo.exe


以前,我使用位字 (fltmc).Count 来检查它。

if ( (fltmc).Count -eq 3 ) { Start powershell.exe "-NoProfile -ExecutionPolicy Bypass -File `"$PSCommandPath`"" -Verb RunAs; exit }
pause

In 2024, If You are running Windows 11 Insider Preview Build 26052 or higher, Windows released the application Sudo for Windows (sudo.exe) which works similar to Unix's Sudo.

  • CLI CMD
sudo.exe cmd.exe
sudo.exe cmd.exe /c "path to batch file"
sudo.exe bcdedit.exe /enum bootmgr
  • CLI PowerShell
sudo.exe powershell.exe
sudo.exe powershell.exe -file "path to ps1 file"
sudo.exe bcdedit.exe /enum bootmgr
  • FILE
sudo.exe cmd.exe /c "%~0"
sudo.exe powershell.exe -file "$PSCommandPath"

More options sudo.exe in Commandline.


Previously, I use a bit word (fltmc).Count to check it.

if ( (fltmc).Count -eq 3 ) { Start powershell.exe "-NoProfile -ExecutionPolicy Bypass -File `"$PSCommandPath`"" -Verb RunAs; exit }
pause
小姐丶请自重 2024-12-15 20:34:10

除了 Shay Levy 的回答之外,请按照以下设置(仅一次)

  1. 以管理员权限启动 PowerShell。
  2. 关注 Stack Overflow 问题PowerShell说“此系统上禁用了脚本的执行。”
  3. 例如,将 .ps1 文件放入任何 PATH 文件夹中。 Windows\System32 文件夹

设置完成后:

  1. Win + R
  2. 调用 powershell Start-Process powershell -Verb runAs

您现在可以运行一切都在一个命令行中。以上适用于 Windows 8 Basic 64 位。

On top of Shay Levy's answer, follow the below setup (just once)

  1. Start a PowerShell with Administrator rights.
  2. Follow Stack Overflow question PowerShell says “execution of scripts is disabled on this system.”.
  3. Put your .ps1 file in any of the PATH folders, for example. Windows\System32 folder

After the setup:

  1. Press Win + R
  2. Invoke powershell Start-Process powershell -Verb runAs <ps1_file>

You can now run everything in just one command line. The above works on Windows 8 Basic 64-bit.

拥有 2024-12-15 20:34:10

我以前没有见过自己的做法,所以,尝试一下。它更容易遵循并且占用空间更小:

if([bool]([Security.Principal.WindowsIdentity]::GetCurrent()).Groups -notcontains "S-1-5-32-544") {
    Start Powershell -ArgumentList "& '$MyInvocation.MyCommand.Path'" -Verb runas
    }

非常简单,如果使用管理员权限调用当前的 Powershell 会话,当您获取当前身份时,管理员组众所周知的 SID 将显示在组中。即使该帐户是该组的成员,SID 也不会显示,除非使用提升的凭据调用该进程。

几乎所有这些答案都是微软的本·阿姆斯特朗(Ben Armstrong)非常流行的方法的变体,该方法如何完成它,但没有真正掌握它实际在做什么以及如何模仿相同的例程。

I haven't seen my own way of doing it before, so, try this out. It is way easier to follow and has a much smaller footprint:

if([bool]([Security.Principal.WindowsIdentity]::GetCurrent()).Groups -notcontains "S-1-5-32-544") {
    Start Powershell -ArgumentList "& '$MyInvocation.MyCommand.Path'" -Verb runas
    }

Very simply, if the current Powershell session was called with administrator privileges, the Administrator Group well-known SID will show up in the Groups when you grab the current identity. Even if the account is a member of that group, the SID won't show up unless the process was invoked with elevated credentials.

Nearly all of these answers are a variation on Microsoft's Ben Armstrong's immensely popular method of how to accomplish it while not really grasping what it is actually doing and how else to emulate the same routine.

少跟Wǒ拽 2024-12-15 20:34:10

要将命令的输出附加到包含当前日期的文本文件名,您可以执行以下操作:

$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 }

To append the output of the command to a text filename which includes the current date you can do something like this:

$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 }
ぃ双果 2024-12-15 20:34:10

这是一个澄清...

powershell RUNAS / SAVECRED 凭据“不安全”,尝试了一下,它将管理员身份和密码添加到凭据缓存中,并且可以在其他地方使用 OOPS!如果您已这样做,我建议您检查并删除该条目。

检查您的程序或代码,因为 Microsoft 政策是如果没有 UAC(入口点)以管理员身份执行程序,则不能在同一代码 blob 中混合用户和管理员代码。这与 Linux 上的 sudo (相同)。

UAC 有 3 种类型,不可见,提示或在程序清单中生成的入口点。它不会提升程序,因此如果没有 UAC 并且需要管理员,它将失败。尽管作为管理员要求,UAC 很好,但它会阻止未经身份验证的代码执行,并阻止在用户级别执行混合代码场景。

This is a clarification ...

The powershell RUNAS / SAVECRED credential "is not safe", tried it and it adds the admin identity and password into the credential cache and can be used elsewhere OOPS!. If you have done this I suggest you check and remove the entry.

Review your program or code because the Microsoft policy is you cannot have mixed user and admin code in the same code blob without the UAC (the entry point) to execute the program as admin. This would be sudo (same thing) on Linux.

The UAC has 3 types, dont'see, a prompt or an entry point generated in the manifest of the program. It does not elevate the program so if there is no UAC and it needs admin it will fail. The UAC though as an administrator requirement is good, it prevents code execution without authentication and prevents the mixed codes scenario executing at user level.

蓝眼泪 2024-12-15 20:34:10

从“开始”>“运行”提升 PowerShell

在 2012R2 或 2016 中,如果不进行两次脱壳操作,则无法通过“运行”命令运行提升的 powershell:

C:\Windows\SysWOW64\WindowsPowerShell\v1.0\powershell -Command “saps PowerShell -动词 RunAs ”

Elevated PowerShell from Start>Run

You cannot run elevated powershell from the "run" command, in 2012R2 or 2016, without shelling twice:

C:\Windows\SysWOW64\WindowsPowerShell\v1.0\powershell -Command "saps PowerShell -Verb RunAs "

浅浅淡淡 2024-12-15 20:34:10

如果你想设置管理员powershell窗口的位置,你可以执行以下操作(我在任何地方都找不到这个)

if (!([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator")) 
{
    Write-Host "Running as non-administrator, restarting as administrator...";
    $powershell = if($PSVersionTable.PSVersion.Major -gt 5) { "pwsh.exe" } else { "powershell.exe" };
    #$arguments = ($PsBoundParameters.GetEnumerator() | ForEach-Object { "-$($_.Key) `"$($_.Value)`"" }) -join " ";
    Start-Process $powershell -Verb RunAs -ArgumentList "-NoExit -NoProfile -ExecutionPolicy Bypass -Command `"Set-Location c:\\`"";
}

或者将启动位置设置为你的桌面

if (!([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator")) 
{
    Write-Host "Running as non-administrator, restarting as administrator...";
    $desktopPath = "C:\Users\$($env:username)\Desktop";
    $powershell = if($PSVersionTable.PSVersion.Major -gt 5) { "pwsh.exe" } else { "powershell.exe" };
    #$arguments = ($PsBoundParameters.GetEnumerator() | ForEach-Object { "-$($_.Key) `"$($_.Value)`"" }) -join " ";
    Start-Process $powershell -Verb RunAs -ArgumentList "-NoExit -NoProfile -ExecutionPolicy Bypass -Command `"Set-Location $($desktopPath)`"";
}

If you want to set the location of the administrator powershell window, you can do the following (I couldn't find this anywhere)

if (!([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator")) 
{
    Write-Host "Running as non-administrator, restarting as administrator...";
    $powershell = if($PSVersionTable.PSVersion.Major -gt 5) { "pwsh.exe" } else { "powershell.exe" };
    #$arguments = ($PsBoundParameters.GetEnumerator() | ForEach-Object { "-$($_.Key) `"$($_.Value)`"" }) -join " ";
    Start-Process $powershell -Verb RunAs -ArgumentList "-NoExit -NoProfile -ExecutionPolicy Bypass -Command `"Set-Location c:\\`"";
}

or to set the startup location as your desktop for example

if (!([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator")) 
{
    Write-Host "Running as non-administrator, restarting as administrator...";
    $desktopPath = "C:\Users\$($env:username)\Desktop";
    $powershell = if($PSVersionTable.PSVersion.Major -gt 5) { "pwsh.exe" } else { "powershell.exe" };
    #$arguments = ($PsBoundParameters.GetEnumerator() | ForEach-Object { "-$($_.Key) `"$($_.Value)`"" }) -join " ";
    Start-Process $powershell -Verb RunAs -ArgumentList "-NoExit -NoProfile -ExecutionPolicy Bypass -Command `"Set-Location $($desktopPath)`"";
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文