Saltar al contenido

La tubería de PowerShell agrega salto de línea

Hola, tenemos la respuesta a tu búsqueda, desplázate y la verás un poco más abajo.

Solución:

Introducción

Aquí está mi Invoke-RawPipeline función (obtenga la última versión de este Gist).

Úselo para canalizar datos binarios entre los flujos de entrada y salida estándar de los procesos. Puede leer el flujo de entrada de un archivo / canalización y guardar el flujo de salida resultante en un archivo.

Requiere el módulo PsAsync para poder lanzar y canalizar datos en múltiples procesos.

En caso de problemas, utilice -Verbose cambie para ver la salida de depuración.

Ejemplos de

Redirigiendo al archivo

  • Lote:
    findstr.exe /C:"Warning" /I C:WindowsWindowsUpdate.log > C:WU_Warnings.txt
  • Potencia Shell:
    Invoke-RawPipeline -Command @Path = 'findstr.exe' ; Arguments = '/C:"Warning" /I C:WindowsWindowsUpdate.log' -OutFile 'C:WU_Warnings.txt'

Redirigiendo desde archivo

  • Lote:
    svnadmin load < C:RepoDumpsMyRepo.dump
  • Potencia Shell:
    Invoke-RawPipeline -InFile 'C:RepoDumpsMyRepo.dump' -Command @Path = 'svnadmin.exe' ; Arguments = 'load'

Cuerdas de tubería

  • Lote:
    echo TestString | find /I "test" > C:SearchResult.log
  • Potencia Shell:
    'TestString' | Invoke-RawPipeline -Command @Path = 'find.exe' ; Arguments = '/I "test"' -OutFile 'C:SearchResult.log'

Tubería entre múltiples procesos

  • Lote:
    ipconfig | findstr /C:"IPv4 Address" /I
  • Potencia Shell:
    Invoke-RawPipeline -Command @Path = 'ipconfig', @Path = 'findstr' ; Arguments = '/C:"IPv4 Address" /I' -RawData

Código:

<#
.Synopsis
    Pipe binary data between processes' Standard Output and Standard Input streams.
    Can read input stream from file and save resulting output stream to file.

.Description
    Pipe binary data between processes' Standard Output and Standard Input streams.
    Can read input stream from file/pipeline and save resulting output stream to file.
    Requires PsAsync module: http://psasync.codeplex.com

.Notes
    Author: beatcracker (https://beatcracker.wordpress.com, https://github.com/beatcracker)
    License: Microsoft Public License (http://opensource.org/licenses/MS-PL)

.Component
    Requires PsAsync module: http://psasync.codeplex.com

.Parameter Command
    An array of hashtables, each containing Command Name, Working Directory and Arguments

.Parameter InFile
    This parameter is optional.

    A string representing path to file, to read input stream from.

.Parameter OutFile
    This parameter is optional.

    A string representing path to file, to save resulting output stream to.

.Parameter Append
    This parameter is optional. Default is false.

    A switch controlling wheither ovewrite or append output file if it already exists. Default is to overwrite.

.Parameter IoTimeout
    This parameter is optional. Default is 0.

    A number of seconds to wait if Input/Output streams are blocked. Default is to wait indefinetely.

.Parameter ProcessTimeout
    This parameter is optional. Default is 0.

    A number of seconds to wait for process to exit after finishing all pipeline operations. Default is to wait indefinetely.
    Details: https://msdn.microsoft.com/en-us/library/ty0d8k56.aspx

.Parameter BufferSize
    This parameter is optional. Default is 4096.

    Size of buffer in bytes for readwrite operations. Supports standard Powershell multipliers: KB, MB, GB, TB, and PB.
    Total number of buffers is: Command.Count * 2 + InFile + OutFile.

.Parameter ForceGC
    This parameter is optional.

    A switch, that if specified will force .Net garbage collection.
    Use to immediately release memory on function exit, if large buffer size was used.

.Parameter RawData
    This parameter is optional.

    By default function returns object with StdOut/StdErr streams and process' exit codes.
    If this switch is specified, function will return raw Standard Output stream.

.Example
    Invoke-RawPipeline -Command @Path = 'findstr.exe' ; Arguments = '/C:"Warning" /I C:WindowsWindowsUpdate.log' -OutFile 'C:WU_Warnings.txt'

    Batch analog: findstr.exe /C:"Warning" /I C:WindowsWindowsUpdate.log' > C:WU_Warnings.txt

.Example
    Invoke-RawPipeline -Command @Path = 'findstr.exe' ; WorkingDirectory = 'C:Windows' ; Arguments = '/C:"Warning" /I .WindowsUpdate.log' -RawData

    Batch analog: cd /D C:Windows && findstr.exe /C:"Warning" /I .WindowsUpdate.log

.Example
    'TestString' | Invoke-RawPipeline -Command @Path = 'find.exe' ; Arguments = '/I "test"' -OutFile 'C:SearchResult.log'

    Batch analog: echo TestString | find /I "test" > C:SearchResult.log

.Example
    Invoke-RawPipeline -Command @Path = 'ipconfig', @Path = 'findstr' ; Arguments = '/C:"IPv4 Address" /I' -RawData

    Batch analog: ipconfig | findstr /C:"IPv4 Address" /I

.Example
    Invoke-RawPipeline -InFile 'C:RepoDumpsRepo.svn' -Command @Path = 'svnadmin.exe' ; Arguments = 'load'

    Batch analog: svnadmin load < C:RepoDumpsMyRepo.dump
#>

function Invoke-RawPipeline

    [CmdletBinding()]
    Param
    (
        [Parameter(ValueFromPipeline = $true)]
        [ValidateNotNullOrEmpty()]
        [ValidateScript(
            if($_.psobject.Methods.Match.('ToString'))
            
                $true
            
            else
            
                throw 'Can''t convert pipeline object to string!'
            
        )]
        $InVariable,

        [Parameter(ValueFromPipelineByPropertyName = $true)]
        [ValidateScript(
            $_ )]
        [ValidateNotNullOrEmpty()]
        [array]$Command,

        [Parameter(ValueFromPipelineByPropertyName = $true)]
        [ValidateScript(
            if(!(Test-Path -LiteralPath $_))
            
                throw "File not found: $_"
            
            $true
        )]
        [ValidateNotNullOrEmpty()]
        [string]$InFile,

        [Parameter(ValueFromPipelineByPropertyName = $true)]
        [ValidateScript(
            if(!(Test-Path -LiteralPath (Split-Path $_)))
            
                throw "Folder not found: $_"
            
            $true
        )]
        [ValidateNotNullOrEmpty()]
        [string]$OutFile,

        [Parameter(ValueFromPipelineByPropertyName = $true)]
        [switch]$Append,

        [Parameter(ValueFromPipelineByPropertyName = $true)]
        [ValidateRange(0, 2147483)]
        [int]$IoTimeout = 0,

        [Parameter(ValueFromPipelineByPropertyName = $true)]
        [ValidateRange(0, 2147483)]
        [int]$ProcessTimeout = 0,

        [Parameter(ValueFromPipelineByPropertyName = $true)]
        [long]$BufferSize = 4096,

        [Parameter(ValueFromPipelineByPropertyName = $true)]
        [switch]$RawData,

        [Parameter(ValueFromPipelineByPropertyName = $true)]
        [switch]$ForceGC
    )

    Begin
    

        $Modules = @PsAsync = 'http://psasync.codeplex.com'

        'Loading modules:', ($Modules 

    Process
     Where-Object !$_.Completed) # Loop until all pipelines are finished

        Write-Verbose 'Waiting for all pipelines to finish...'
        $IoStats = Receive-AsyncResults -Pipelines $AsyncPipelines
        Write-Verbose 'All pipelines are finished'

        Write-Verbose 'Collecting StdErr for all processes'
        $PipeStdErr = $StdErrWorkers 

Enfoque de fuerza bruta: alimente datos binarios para procesar 'stdin. He probado este código en el cat.exe de UnixUtils y parece hacer lo que quieres:

# Text to send
$InputVar = "No Newline, No NewLine,`nNewLine, No NewLine,`nNewLine, No NewLine"

# Buffer & initial size of MemoryStream
$BufferSize = 4096

# Convert text to bytes and write to MemoryStream
[byte[]]$InputBytes = [Text.Encoding]::UTF8.GetBytes($InputVar)
$MemStream = New-Object -TypeName System.IO.MemoryStream -ArgumentList $BufferSize
$MemStream.Write($InputBytes, 0, $InputBytes.Length)
[Void]$MemStream.Seek(0, 'Begin')

# Setup stdinstdout redirection for our process
$StartInfo = New-Object -TypeName System.Diagnostics.ProcessStartInfo -Property @
                FileName = 'MyLittle.exe'
                UseShellExecute = $false
                RedirectStandardInput = $true
            

# Create new process
$Process = New-Object -TypeName System.Diagnostics.Process

# Assign previously created StartInfo properties
$Process.StartInfo = $StartInfo
# Start process
[void]$Process.Start()

# Pipe data
$Buffer = New-Object -TypeName byte[] -ArgumentList $BufferSize
$StdinStream = $Process.StandardInput.BaseStream

try

    do
    
        $ReadCount = $MemStream.Read($Buffer, 0, $Buffer.Length)
        $StdinStream.Write($Buffer, 0, $ReadCount)
        $StdinStream.Flush()
    
    while($ReadCount -gt 0)

catch

    throw 'Houston, we have a problem!'           

finally

    # Close streams
    $StdinStream.Close()
    $MemStream.Close()


# Cleanup
'Process', 'StdinStream', 'MemStream' |
    ForEach-Object 
        (Get-Variable $_ -ValueOnly).Dispose()
        Remove-Variable $_ -Force
    

No se te olvide dar difusión a este ensayo si te ayudó.

¡Haz clic para puntuar esta entrada!
(Votos: 0 Promedio: 0)



Utiliza Nuestro Buscador

Deja una respuesta

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *