Tee-Object沒有-NoNewline像許多其他輸出到檔案 cmdlet 那樣的開關(例如Out-File,Set-Content)。在 hood 下,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..
不幸的是,其中包含額外的位元組,0D 0A也就是`r`nWindows 中的 CR&LF。
uj5u.com熱心網友回復:
您可以自己動手并撰寫一個帶前綴的換行符:
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,上面的函式處于永久“追加模式”。重構它以支持附加和覆寫都留給讀者練習:)
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/380564.html
標籤:电源外壳 新队 球座 尾随换行 powershell-7.2
