将Powershell输出重定向到.ps1

时间:2012-12-28 10:21:11

标签: powershell-v2.0

我使用powershell来调用sql存储过程,现在我想将整个输出集重定向到.ps1文件,因为输出行在powershell中是可执行的。

我正在尝试使用> output.ps1,它可以工作,但我正在检查输出文件,它包含很多'...'来替换实际输出。

如何导出完整输出?关闭标题?

感谢。

1 个答案:

答案 0 :(得分:0)

这取决于您如何调用存储过程。如果您在PowerShell中调用它,您应该能够收集输出,因此我假设您将其作为一个单独的任务启动它自己的窗口。如果没有您的实际示例,这里有一种从tasklist.exe命令收集输出的方法。您可能会发现它适用。

cls
$exe = 'c:\Windows\System32\tasklist.exe'
$processArgs = '/NH'
try {
    Write-Host ("Launching '$exe $processArgs'")
    $info = New-Object System.Diagnostics.ProcessStartInfo
    $info.UseShellExecute = $false 
    $info.RedirectStandardError = $true 
    $info.RedirectStandardOutput = $true 
    $info.RedirectStandardInput = $true 
    $info.WindowStyle = [System.Diagnostics.ProcessWindowStyle]::Hidden
    $info.CreateNoWindow = $true
    $info.ErrorDialog = $false
    $info.WorkingDirectory = $workingDir
    $info.Filename = $exe
    $info.Arguments = $processArgs

    $process = [System.Diagnostics.Process]::Start($info)
    Write-Host ("Launched $($process.Id) at $(Get-Date)")
    <# 
    $process.StandardOutput.ReadToEnd() is a synchronous read. You cannot sync read both output and error streams. 
    $process.BeginOutputReadLine() is an async read. You can do as many of these as you'd like. 
    Either way, you must finish reading before calling $process.WaitForExit()
    http://msdn.microsoft.com/en-us/library/system.diagnostics.processstartinfo.redirectstandardoutput.aspx
    #>

    $output = $process.StandardOutput.ReadToEnd()

    $process.WaitForExit() | Out-Null 

    Write-Host ("Exited at $(Get-Date)`n$output")

} catch {
    Write-Host ("Failed to launch '$exe $processArgs'")
    Write-Host ("Failure due to $_")
}
$output