c# - 如何启动一个新的 powershell 实例并在其中运行命令?

标签 c# powershell

这就是我想要完成的:

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

此函数目前将在提升模式下创建并运行一个新的 Powershell 对象。

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
}

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

如有任何关于语法的提示,我们将不胜感激。

最佳答案

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

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>
    }
}

关于c# - 如何启动一个新的 powershell 实例并在其中运行命令?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20642502/

相关文章:

Powershell 在 If 语句中尝试使用 -and 时出错

azure - 将带有标签的 Azure 资源组导出到 csv

C# 静态类成员和 System.Windows.Controls.Image 性能问题

C# 静态构造函数在填充 ConcurrentDictionary 时初始化线程安全

c# - XML反序列化泛型方法

powershell - 带有 Invoke-Expression 的 powershell 的标准错误和标准输出没有输出或错误

powershell - 内部的Trim值(内部的一个数组(twoDimentionalArray))

powershell - 如何使用 PowerShell 处理 diskpart 命令的输出

c# - 如何使用 Coypu 和 C# 获取 InnerText?

c# - C# 应用程序中的 SerialPort 问题