Powershell将stderr和stdout重定向到两个不同的地方

时间:2017-07-13 04:43:09

标签: powershell redirect stdout stderr

如何重定向

  • stderr to logfile
  • stdout to object

我看过的事情:

>>2>>仅重定向到文件  -RedirectStandardOutput-RedirectStandardError仅重定向到文件。
 | Out-File无法重定向stderr  | Tee-Object同样的问题。

3 个答案:

答案 0 :(得分:6)

加入## dictionary initialization >>> tel = {'jack': 4098, 'sape': 4139} ## set value for a key (either existing or new) >>> tel['guido'] = 4127 ## print dictionary >>> tel {'sape': 4139, 'guido': 4127, 'jack': 4098} ## get value for an existing key >>> tel['jack'] 4098 ## delete a key from dictionary >>> del tel['sape'] ## add a new key with value >>> tel['irv'] = 4127 ## print dictionary >>> tel {'guido': 4127, 'irv': 4127, 'jack': 4098} ## get all keys in dictionary >>> list(tel.keys()) ['irv', 'guido', 'jack'] ## get all keys in dictionary (sorted) >>> sorted(tel.keys()) ['guido', 'irv', 'jack'] ## check if a key exists in dictionary >>> 'guido' in tel True ## check if a key exists in dictionary >>> 'jack' not in tel False ## Finally iterating thru dictionary for key, value in tel.items(): print(key, value) stdout输出流的工作方式与PetSerAl相同,但语法不是最直观的。

stderr的奇怪语法意味着2>&1(流2)将被添加到stderr(流1)中。由于这实际上并非您所追求的,请尝试将MS页面中的另一个示例调整为Powershell:

  

或者,您可以将输出重定向到一个位置,将错误重定向到另一个位置。

     

dir file.xxx> output.msg 2> output.err

因此,

stdout

应该在日志文件中发送错误,在$ret = myCommand 2> errors.log 变量中发送非错误。

答案 1 :(得分:2)

about_Redirection MSDN文章中的全面解释。

A Minimal, Complete, and Verifiable example class nullDoubleRate extends UserDefinedAggregateFunction { override def inputSchema : StructType = StructType(Array(StructField("value", DoubleType, true))) override def bufferSchema : StructType = StructType(Array( StructField("count", IntegerType, true), StructField("total", IntegerType, true) )) override def dataType : DataType = DoubleType override def deterministic : Boolean = true override def initialize(buffer : MutableAggregationBuffer) : Unit = { buffer(0) = 0 buffer(1) = 0 } override def update(buffer : MutableAggregationBuffer, input : Row) : Unit = { if (input.isNullAt(0)) { buffer(0) = buffer.getInt(0) + 1 } buffer(1) = buffer.getInt(1) + 1 } override def merge(buffer1 : MutableAggregationBuffer, buffer2 : Row) : Unit = { buffer1(0) = buffer1.getInt(0) + buffer2.getInt(0) buffer1(1) = buffer1.getInt(1) + buffer2.getInt(1) } override def evaluate(buffer : Row) : Double = { 1.0 * buffer.getInt(0) / buffer.getInt(1) } } 来管道):

stdout

另一个例子( PS D:\PShell> -1,5,0,2| ForEach-Object { 15/$_ } 2>"$env:temp\err.txt" | Write-Output -15 3 7.5 PS D:\PShell> Get-Content "$env:temp\err.txt" Attempted to divide by zero. At line:1 char:28 + -1,5,0,2| ForEach-Object { 15/$_ } 2>"$env:temp\err.txt" | Write-Outpu ... + ~~~~~ + CategoryInfo : NotSpecified: (:) [], RuntimeException + FullyQualifiedErrorId : RuntimeException PS D:\PShell> 对象):

stdout

答案 2 :(得分:0)

cls
function GetAnsVal {
    param([Parameter(Mandatory=$true, ValueFromPipeline=$true)][System.Object[]][AllowEmptyString()]$Output,
          [Parameter(Mandatory=$false, ValueFromPipeline=$true)][System.String]$firstEncNew="UTF-8",
          [Parameter(Mandatory=$false, ValueFromPipeline=$true)][System.String]$secondEncNew="CP866"
    )
    function ConvertTo-Encoding ([string]$From, [string]$To){#"UTF-8" "CP866" "ASCII" "windows-1251"
        Begin{
            $encFrom = [System.Text.Encoding]::GetEncoding($from)
            $encTo = [System.Text.Encoding]::GetEncoding($to)
        }
        Process{
            $Text=($_).ToString()
            $bytes = $encTo.GetBytes($Text)
            $bytes = [System.Text.Encoding]::Convert($encFrom, $encTo, $bytes)
            $encTo.GetString($bytes)
        }
    }
    $all = New-Object System.Collections.Generic.List[System.Object];
    $exception = New-Object System.Collections.Generic.List[System.Object];
    $stderr = New-Object System.Collections.Generic.List[System.Object];
    $stdout = New-Object System.Collections.Generic.List[System.Object]
    $i = 0;$Output | % {
        if ($_ -ne $null){
            if ($_.GetType().FullName -ne 'System.Management.Automation.ErrorRecord'){
                if ($_.Exception.message -ne $null){$Temp=$_.Exception.message | ConvertTo-Encoding $firstEncNew $secondEncNew;$all.Add($Temp);$exception.Add($Temp)}
                elseif ($_ -ne $null){$Temp=$_ | ConvertTo-Encoding $firstEncNew $secondEncNew;$all.Add($Temp);$stdout.Add($Temp)}
            } else {
                #if (MyNonTerminatingError.Exception is AccessDeniedException)
                $Temp=$_.Exception.message | ConvertTo-Encoding $firstEncNew $secondEncNew;
                $all.Add($Temp);$stderr.Add($Temp)
            }   
         }
    $i++
    }
    [hashtable]$return = @{}
    $return.Meta0=$all;$return.Meta1=$exception;$return.Meta2=$stderr;$return.Meta3=$stdout;
    return $return
}
Add-Type -AssemblyName System.Windows.Forms;
& C:\Windows\System32\curl.exe 'api.ipify.org/?format=plain' 2>&1 | set-variable Output;
$r = & GetAnsVal $Output
$Meta2=""
foreach ($el in $r.Meta2){
    $Meta2+=$el
}
$Meta2=($Meta2 -split "[`r`n]") -join "`n"
$Meta2=($Meta2 -split "[`n]{2,}") -join "`n"
[Console]::Write("stderr:`n");
[Console]::Write($Meta2);
[Console]::Write("`n");
$Meta3=""
foreach ($el in $r.Meta3){
    $Meta3+=$el
}
$Meta3=($Meta3 -split "[`r`n]") -join "`n"
$Meta3=($Meta3 -split "[`n]{2,}") -join "`n"
[Console]::Write("stdout:`n");
[Console]::Write($Meta3);
[Console]::Write("`n");
相关问题