如何从脚本内提升 Powershell 脚本

Jin*_*nHH 7 powershell

我是 Powershell 的新手,但在很多方面都非常喜欢它。由于某些原因,我创建了一个脚本,该脚本从硬盘驱动器上的文件加载一组本地管理凭据,并创建一个 PSCredential 对象 $MyCred。

我想使用 $MyCred 提升一个单独的脚本(这会进行一些注册表更改以打开 RDP 连接)。我尝试将 $MyCred 传递给 Start-Process cmdlet:

Start-Process Powershell.exe -Credential $MyCredential

然后我收到以下错误:

Start-Process :由于错误,该命令无法运行:目录名称无效。

如果我使用 -credential 和空变量运行启动进程,系统会提示我输入用户名和密码。当我输入它们时,我会得到一个提升的 powershell 提示符,没有任何问题,并且能够在我的测试系统的注册表中进行更改。

我已经验证了 $myCred 的内容,它的 U/N 和 P/W 都正确存储(如,与我手动输入的内容相同)。使用 New-PSSEssion 之类

New-PSSession -Credential $MyCredential

返回访问被拒绝,我读过在很多系统上默认情况下也是禁用的。

在理想的情况下,代码看起来像这样:

Start-Process Powershell.exe -Credential $MyCredential -File C:\MyScript.ps1

这应该启动一个提升的 powershell,在第二个脚本中运行一些命令,然后终止。我在这里缺少什么?

感谢我能得到的所有帮助,谢谢!我可能是完全显而易见的东西。


背景是,我们有一些计算机我们自己无法获得,也无法通过 RDP 访问。我们的站点上确实有可以为我们运行脚本的用户。但重要的是他们无法获得本地管理员密码。因此,我们想要创建一个脚本来读取加密的密码文件,生成本地管理 PSCredential 对象,并将其传递给一个脚本,该脚本进行必要的注册表更改以允许 RDP 访问。

pos*_*ote 12

有许多关于此主题的用例文章。使用“PowerShell 自提升脚本”进行快速网络搜索将显示它们。甚至直接来自 MS

自提升的 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 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")
Run Code Online (Sandbox Code Playgroud)


pro*_*365 0

您在这里错过了 NoExit 参数。

Start-Process -Filepath "Powershell.exe" -ArgumentList "-NoExit -File "C:\myscript.ps1" -Credential $MyCredential 
Run Code Online (Sandbox Code Playgroud)