Powershell以管理员身份运行错误

时间:2020-03-05 23:21:51

标签: powershell administrator runas

尝试在不受限制的计算机上运行此脚本,但是似乎每次都崩溃。在我的计算机上工作正常,这使我认为它可能是基于许可的?不受限制的计算机是运行脚本的本地管理员帐户,它将打开第2个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");

更新:我设法录制了一段视频并捕获了显示的错误:

The expression after '&' in a pipeline element product an object that was not valid. It must result in a command name, a script block, or a commandInfo object.
At line:1 char:3 
+& ''
+  ~~~
+ CategoryInfo : InvalidOperation (:String)[], RuntimeException
+ FullyQulifiedErrorId : BadExpression

0 个答案:

没有答案