【问题标题】:Manually running a .ps1 in an administrator (elevated) shell在管理员(提升的)shell 中手动运行 .ps1
【发布时间】:2014-05-11 03:50:44
【问题描述】:

我有一个看似简单的问题:如何在 Server 2012 R2 上手动运行 .ps1 脚本并在管理员提升的 shell 中打开它?我正在右键单击并单击 .ps1 文件上的“使用 Powershell 运行”。

我的环境:

同一 OU 中同一域中的两台 Server 2012 R2 计算机。两者都是完整的 GUI 安装。两者都将 UAC 设置为“默认”。

差异:

其中一台服务器将在管理员提升的 shell 中运行任何和所有 .ps1 文件。另一台服务器将在非管理员的标准 shell 中运行任何和所有 .ps1 文件。我不知道两台服务器之间有什么区别。两者都没有运行任何自定义 Powershell 配置文件。

以下注册表项在两台服务器之间都是相同的:

HKEY_CLASSES_ROOT\Microsoft.PowerShellCmdletDefinitionXML.1

HKEY_CLASSES_ROOT\Microsoft.PowerShellConsole.1

HKEY_CLASSES_ROOT\Microsoft.PowerShellData.1

HKEY_CLASSES_ROOT\Microsoft.PowerShellModule.1

HKEY_CLASSES_ROOT\Microsoft.PowerShellScript.1

HKEY_CLASSES_ROOT\Microsoft.PowerShellSessionConfiguration.1

HKEY_CLASSES_ROOT\Microsoft.PowerShellXMLData.1

我错过了什么?

【问题讨论】:

  • 我找到了两种解决此问题的方法: 1. 禁用 UAC...我知道,我知道...很明显,对吗?没有! Server 2012 R2 在如何完全禁用 UAC 方面与 2008 不同:social.technet.microsoft.com/wiki/contents/articles/… 2. 在本地安全策略、本地策略、安全选项中,设置“用户帐户控制:对内置管理员帐户使用管理员批准模式”选项" 改为 "禁用" 并重新启动。

标签: powershell windows-server-2012-r2 administrator


【解决方案1】:

与 Google 的一次快速接触最终让我得到了 posting on Ben Armstrong's blog,他在其中发布了代码,如果需要,它会自动提升脚本。这是他发布的代码,似乎非常适合您的需求:

# 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 Administrator"
 if ($myWindowsPrincipal.IsInRole($adminRole))
    {
    # We are running "as Administrator" - so change the title and background color to indicate this
    $Host.UI.RawUI.WindowTitle = $myInvocation.MyCommand.Definition + "(Elevated)"
    $Host.UI.RawUI.BackgroundColor = "DarkBlue"
    clear-host
    }
 else
    {
    # We are not running "as 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
    $newProcess.Arguments = $myInvocation.MyCommand.Definition;

    # 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")

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-01-19
    • 2015-07-20
    • 1970-01-01
    • 2015-12-24
    • 2016-10-23
    • 2015-04-17
    • 1970-01-01
    • 2012-04-28
    相关资源
    最近更新 更多