通过启动进程以管理员身份从 powershell 脚本重定向 stdout、stderr

Sol*_*eil 6 powershell start-process

在 powershell 脚本中,我正在运行一个命令,该命令以管理员身份启动一个新的 powershell(如果我不是,如果需要,取决于$arg),然后运行该脚本。

我正在尝试将 stdout 和 stderr 重定向到第一个终端。

不是试图让事情变得更容易,也有争论。

param([string]$arg="help")

if($arg -eq "start" -Or $arg -eq "stop")
{
    if(![bool](([System.Security.Principal.WindowsIdentity]::GetCurrent()).groups -match "S-1-5-32-544"))
    {
        Start-Process powershell -Verb runas -ArgumentList " -file servicemssql.ps1 $arg"
        exit
    }
}

$Services = "MSSQLSERVER", "SQLSERVERAGENT", "MSSQLServerOLAPService", "SSASTELEMETRY", "SQLBrowser", `
"SQLTELEMETRY", "MSSQLLaunchpad", "SQLWriter", "MSSQLFDLauncher"

function startsql {
    "starting SQL services"
    Foreach ($s in $Services) {
        "starting $s"
        Start-Service -Name "$s"
    }
}

function stopsql {
    "stopping SQL services"
    Foreach ($s in $Services) {
        "stopping $s"
        Stop-Service -Force -Name "$s"
    }
}

function statussql {
    "getting SQL services status"
    Foreach ($s in $Services) {
        Get-Service -Name "$s"
    }
}

function help {
    "usage: StartMssql [status|start|stop]"
}

Switch ($arg) {
    "start" { startsql }
    "stop" { stopsql }
    "status" { statussql }
    "help" { help }
    "h" { help }
}
Run Code Online (Sandbox Code Playgroud)

在 SO 上使用以下答案不起作用:

如何处理双引号内的双引号,同时保留变量 ( $arg) 扩展?

mkl*_*nt0 10

PowerShell 的Start-Processcmdlet:

  • 确实有-RedirectStandardOut-RedirectStandardError参数,
  • 但从语法上讲,它们不能与-Verb Runas,启动提升的进程所需的参数(具有管理权限)结合使用。

此约束也反映在底层 .NET API 中,其中将实例.UseShellExecute上的属性设置System.Diagnostics.ProcessStartInfotrue- 能够使用.Verb = "RunAs"以提升运行的先决条件- 意味着您不能使用.RedirectStandardOutput.RedirectStandardError属性。

总的来说,这表明您不能直接从非提升过程中捕获提升过程的输出流。

一个纯粹的PowerShell的解决方法是不平凡的:

param([string] $arg='help')

if ($arg -in 'start', 'stop') {
  if (-not (([System.Security.Principal.WindowsPrincipal] [System.Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole('Administrators'))) {

    # Invoke the script via -Command rather than -File, so that 
    # a redirection can be specified.
    $passThruArgs = '-command', '&', 'servicemssql.ps1', $arg, '*>', "`"$PSScriptRoot\out.txt`""

    Start-Process powershell -Wait -Verb RunAs -ArgumentList $passThruArgs

    # Retrieve the captured output streams here:
    Get-Content "$PSScriptRoot\out.txt"

    exit
  }
}

# ...
Run Code Online (Sandbox Code Playgroud)
  • 代替-File,-Command用于调用脚本,因为这允许将重定向附加到命令:*>重定向所有输出流。

    • @soleil 建议使用Tee-Object作为替代方案,这样不仅可以捕获提升过程产生的输出,还可以在生成时将其打印到(总是新窗口的)控制台:
      ..., $arg, '|', 'Tee-Object', '-FilePath', "`"$PSScriptRoot\out.txt`""

    • 警告:虽然在这个简单的情况下没有区别,但重要的是要知道参数在-File-Command模式之间的解析方式不同;简而言之, with -File,脚本名称后面的参数被视为文字,而后面的参数-Command形成一个命令,该命令根据目标会话中的正常 PowerShell 规则进行评估,例如,这对转义有影响;值得注意的是,带有嵌入空格的值必须用引号括起来作为值的一部分。

  • $PSScriptRoot\输出捕获文件中的路径组件$PSScriptRoot\out.txt确保该文件与调用脚本在同一文件夹中创建(提升的进程默认$env:SystemRoot\System32为工作目录。)

    • 同样,这意味着脚本文件servicemssql.ps1,如果它在没有路径组件的情况下被调用,则必须位于 中列出的目录之一中$env:PATH,以便提升的 PowerShell 实例找到它;否则,还需要完整路径,例如$PSScriptRoot\servicemssql.ps1.
  • -Wait确保在提升的进程退出之前控制权不会返回,此时$PSScriptRoot\out.txt可以检查文件。


至于后续问题:

更进一步,我们是否有办法让管理 shell 运行不可见,并在我们使用 Unix 等效tail -f的非特权 shell 时读取文件?

可以在不可见的情况下运行提升的进程本身,但请注意,您仍然会收到 UAC 确认提示。(如果您要关闭 UAC(不推荐),您可以使用Start-Process -NoNewWindow在同一窗口中运行该进程。)

为了在生成时监视输出,tail -f-style,仅 PowerShell 的解决方案既重要又不是最有效的;以机智:

param([string]$arg='help')

if ($arg -in 'start', 'stop') {
  if (-not (([System.Security.Principal.WindowsPrincipal] [System.Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole('Administrators'))) {

    # Delete any old capture file.
    $captureFile = "$PSScriptRoot\out.txt"
    Remove-Item -ErrorAction Ignore $captureFile

    # Start the elevated process *hidden and asynchronously*, passing
    # a [System.Diagnostics.Process] instance representing the new process out, which can be used
    # to monitor the process
    $passThruArgs = '-noprofile', '-command', '&',  "servicemssql.ps1", $arg, '*>', $captureFile
    $ps = Start-Process powershell -WindowStyle Hidden -PassThru  -Verb RunAs -ArgumentList $passThruArgs

    # Wait for the capture file to appear, so we can start
    # "tailing" it.
    While (-not $ps.HasExited -and -not (Test-Path -LiteralPath $captureFile)) {
      Start-Sleep -Milliseconds 100  
    }

    # Start an aux. background that removes the capture file when the elevated
    # process exits. This will make Get-Content -Wait below stop waiting.
    $jb = Start-Job { 
      # Wait for the process to exit.
      # Note: $using:ps cannot be used directly, because, due to
      #       serialization/deserialization, it is not a live object.
      $ps = (Get-Process -Id $using:ps.Id)
      while (-not $ps.HasExited) { Start-Sleep -Milliseconds 100 }
      # Get-Content -Wait only checks once every second, so we must make
      # sure that it has seen the latest content before we delete the file.
      Start-Sleep -Milliseconds 1100 
      # Delete the file, which will make Get-Content -Wait exit (with an error).
      Remove-Item -LiteralPath $using:captureFile 
    }

    # Output the content of $captureFile and wait for new content to appear
    # (-Wait), similar to tail -f.
    # `-OutVariable capturedLines` collects all output in
    # variable $capturedLines for later inspection.
    Get-Content -ErrorAction SilentlyContinue -Wait -OutVariable capturedLines -LiteralPath $captureFile

    Remove-Job -Force $jb  # Remove the aux. job

    Write-Verbose -Verbose "$($capturedLines.Count) line(s) captured."

    exit
  }
}

# ...
Run Code Online (Sandbox Code Playgroud)