【问题标题】:Self Elevating Script + Execution Policy自提升脚本 + 执行策略
【发布时间】:2017-03-05 14:19:15
【问题描述】:

我正在尝试使用来自问题"PowerShell: Running a command as Administrator" 的以下代码,不仅可以自我提升我的脚本以在管理员级别的 PowerShell 中自动运行,而且还可以使用 ExecutionPolicy 运行管理员级别的 PowerShell 会话RemoteSigned 的级别。我假设我需要在$newProcess.Arguments 中使用-ExecutionPolicy RemoteSigned 之类的东西,但我完全不知道是否是这种情况,如果是这种情况,那么我使用什么语法来创建多个参数?

# 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 会话运行脚本,该脚本将限制单个可执行文件的 Internet 带宽。我的理解是,这只能通过管理员级别的 Powershell 脚本来实现。我还需要它能够在默认 ExecutionPolicy 设置为 Restricted 的 Windows 10 机器上运行。因此,我希望在脚本执行期间降低 ExecutionPolicy 的级别。

标签: powershell administrator executionpolicy


【解决方案1】:

$newProcess.Arguments 确实是您添加相关参数的地方。但是,您可能希望通过参数 -File 运行脚本,而不是在隐式 -Command 参数中使用调用运算符 (&)。

$newProcess = New-Object Diagnostics.ProcessStartInfo 'powershell.exe'
$newProcess.Arguments = '-ExecutionPolicy RemoteSigned -File "' +
                        $script:MyInvocation.MyCommand.Path + '"'
$newProcess.Verb = 'runas'
[Diagnostics.Process]::Start($newProcess)

【讨论】:

  • 太完美了——完全符合我的期望。今天早上花了几个小时把我的头发扯掉后,你很快就为我解决了。谢谢你:)
猜你喜欢
  • 1970-01-01
  • 2016-11-11
  • 1970-01-01
  • 2021-10-26
  • 2019-11-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多