1

Tee-Object没有-NoNewline像许多其他输出到文件 cmdlet 那样的开关(例如Out-File, Set-Content)。在幕后Tee-Object用于Out-File写入文件,默认情况下添加尾随换行符。

由于我(当前)无法通过-NoNewlineswitch through Tee-Object,是否有另一种方法可以强制底层Out-File不会添加尾随换行符?看看 的实现Out-File,现在可能有办法,但也许有人知道一些技巧/黑客来实现它?

一些限制:

  • 我想Tee-Object在管道中使用(或替代解决方案)
  • 我不想对由Tee-Object(或替代解决方案)生成的文件进行后处理,例如再次打开它们并删除(最后一个)换行符。

复制代码:

"Test" | Tee-Object file | Out-Null

在 Windows 上,生成的文件file将包含 6 个字节,如以下 hexdump 所示:

          00 01 02 03 04 05 06 07 08 09 0A 0B 0C 0D 0E 0F ASCII
00000000  54 65 73 74 0D 0A                               Test..

不幸的是,其中包含 Windows 中的附加字节0D 0Aaka`r`n或 CR&LF。

4

1 回答 1

2

您可以自己滚动并编写一个带前缀的换行符:

function Tee-StackProtectorObject {
    param(
        [Parameter(Mandatory=$true, Position=1, ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true)]
        [AllowNull()]
        [AllowEmptyCollection()]
        [psobject]
        $InputObject,

        [Parameter(ParameterSetName='Path', Mandatory=$true, Position=0, ValueFromPipelineByPropertyName=$true)]
        [string[]]
        $Path,

        [Parameter(ParameterSetName='LiteralPath', Mandatory=$true, ValueFromPipelineByPropertyName=$true)]
        [Alias('PSPath')]
        [string[]]
        $LiteralPath
    )

    begin {
        # Determine newline character sequence at the start (might differ across platforms)
        $newLine = [Environment]::NewLine

        # Prepare parameter arguments for Add-Content
        $addContentParams = @{ NoNewLine = $true }
        if($PSCmdlet.ParameterSetName -eq 'Path'){
            $addContentParams['Path'] = $Path
        }
        else {
            $addContentParams['LiteralPath'] = $LiteralPath
        }
    }

    process {
        # Write to file twice - first a newline, then the content without trailling newline
        Add-Content -Value $newLine @addContentParams
        Add-Content -Value $InputObject @addContentParams

        # Write back to pipeline
        Write-Output -InputObject $InputObject
    }
}

请注意,与 不同Tee-Object的是,上述函数处于永久“附加模式”。重构它以支持附加和覆盖作为练习留给读者:)

于 2021-12-14T13:49:15.923 回答