powershell - 自提升脚本+执行策略

标签 powershell administrator executionpolicy

我正在尝试使用问题 "PowerShell: Running a command as Administrator" 中的以下代码不仅可以 self 提升我的脚本以在管理员级别 PowerShell 中自动运行,还可以使管理员级别 PowerShell session 以 RemoteSigned 的 ExecutionPolicy 级别运行。我假设我需要在 $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");

最佳答案

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

关于powershell - 自提升脚本+执行策略,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40207676/

相关文章:

Powershell Invoke-SQLCmd 和 SQLPS

PowerShell 错误记录为空/不正确 'InvocationInfo'

.net - PowerShell:创建自定义异常

java - 通过java代码以管理员身份从cmd运行应用程序

delphi - Word 自动化仅适用于管理员,或者在创建 word.application 后会出现延迟

azure - 如何使用 PowerShell 将 Api 权限添加到 Azure 应用程序注册

windows - 如何在 PowerShell 脚本中向用户提供可供选择的打印机列表?

c# - 如何以编程方式将用户设置为 SharePoint 中的网站集管理员

c# - 为什么从 C# 中看不到从 PowerShell 设置的新执行策略?