PowerShell's pipe adds linefeed

前端 未结 5 1275
醉梦人生
醉梦人生 2021-02-07 05:45

I\'m trying to pipe a string into a program\'s STDIN without any trailing linefeeds (unless that string itself actually ends in a linefeed). I tried googling around, bu

5条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-02-07 06:37

    Bruteforce approach: feed binary data to process' stdin. I've tested this code on the cat.exe from UnixUtils and it seems to do what you want:

    # 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 stdin\stdout 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
        }
    

提交回复
热议问题