在管理员(提升)shell中手动运行.ps1

时间:2014-03-31 17:06:31

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

我有一个看似简单的问题:如何在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 个答案:

答案 0 :(得分:2)

谷歌的一次快速尝试最终导致了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")