如何启动一个新的 powershell 实例并在其中运行命令? [英] How do I start a new powershell instance and run commands in it?

查看:154
本文介绍了如何启动一个新的 powershell 实例并在其中运行命令?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这就是我想要完成的:

我需要一个用户在登录计算机时自动运行一个powershell脚本,让脚本启动一个提升的Powershell提示(就像用户可以点击以管理员身份运行Powershell一样)然后让它运行一些命令在新的 Powershell 对象中,然后关闭新的 Powershell 对象.

I need a user to automatically run a powershell script when he logs into the computer, have the script start an Elevated Powershell Prompt(the same as if the user could click on Run Powershell as Administrator) and then have it run some commands in the new Powershell Object, then close the new Powershell object.

此函数当前将在 Elevated 模式下创建并运行一个新的 Powershell 对象.

This function currently will create and run a new Powershell object in Elevated mode.

function Set-Elevation
{
   # Create a new process object that starts PowerShell
   $newProcess = New-Object System.Diagnostics.ProcessStartInfo "powershell";
   # Indicate that the process should be elevated
   $newProcess.Verb = "runas";
   # Start the new process
   [System.Diagnostics.Process]::Start($newProcess) | Out-Null
}

但是,我如何让它在那里运行新命令?之后我将如何关闭对象?

However, how would I get it to run new commands in there? And how would I close the object afterward?

任何有关语法的提示将不胜感激.

Any tips on the syntax would be appreciated.

推荐答案

您可以使用内置的 Start-Process 命令:

You can use the built-in Start-Process command:

function IsAdministrator
{
    $Identity = [System.Security.Principal.WindowsIdentity]::GetCurrent()
    $Principal = New-Object System.Security.Principal.WindowsPrincipal($Identity)
    $Principal.IsInRole([System.Security.Principal.WindowsBuiltInRole]::Administrator)
}

function IsUacEnabled
{
    (Get-ItemProperty HKLM:\Software\Microsoft\Windows\CurrentVersion\Policies\System).EnableLua -ne 0
}

#
# Main script
#
if (!(IsAdministrator))
{
    if (IsUacEnabled)
    {
        [string[]]$argList = @('-NoProfile', '-NoExit', '-File', $MyInvocation.MyCommand.Path)
        $argList += $MyInvocation.BoundParameters.GetEnumerator() | Foreach {"-$($_.Key)", "$($_.Value)"}
        $argList += $MyInvocation.UnboundArguments
        Start-Process PowerShell.exe -Verb Runas -WorkingDirectory $pwd -ArgumentList $argList 
        return
    }
    else
    {
        # Log an error, do nothing or Start-Process -Credentials <admin_creds>
    }
}

这篇关于如何启动一个新的 powershell 实例并在其中运行命令?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆