防止在PowerShell Out文件命令中拖尾换行符
如何防止PowerShell的命令在输出的文本后追加换行符 例如,运行以下命令会生成一个内容为“TestTest\r\n”的文件,而不仅仅是“TestTest”防止在PowerShell Out文件命令中拖尾换行符,powershell,powershell-2.0,Powershell,Powershell 2.0,如何防止PowerShell的命令在输出的文本后追加换行符 例如,运行以下命令会生成一个内容为“TestTest\r\n”的文件,而不仅仅是“TestTest” 在PowerShell 5.0+中,您将使用: "TestTest" | Out-File -encoding ascii test.txt -NoNewline 但在早期版本中,您无法使用该cmdlet 试试这个: [System.IO.File]::WriteAllText($FilePath,"TestTest",[System
在PowerShell 5.0+中,您将使用:
"TestTest" | Out-File -encoding ascii test.txt -NoNewline
但在早期版本中,您无法使用该cmdlet
试试这个:
[System.IO.File]::WriteAllText($FilePath,"TestTest",[System.Text.Encoding]::ASCII)
要补充re-NoNewline
:
以下内容不仅适用于输出文件
,还类似于设置内容
/添加内容
;如上所述,-NoNewline
需要PSv5+
请注意,-NoNewline
意味着当要输出多个对象时,被抑制的不仅仅是尾随换行符(换行符),而是任何换行符
换句话说:输入对象的字符串表示是直接连接的,没有分隔符(终止符)
因此,以下命令会产生相同的文件内容(TestTest
无尾随换行):
为了仅在输出对象之间放置新行,而不在输出对象之后放置新行,必须将对象与新行显式地连接起来:
"Test", "Test" -join [Environment]::NewLine |
Out-File -encoding ascii test.txt -NoNewline
[Environment]:换行符
是适合平台的换行符序列(Windows上的CRLF,类Unix平台上的LF);如果需要,还可以使用“`r`n”
和“`n”
警告:
"Test", "Test" -join [Environment]::NewLine |
Out-File -encoding ascii test.txt -NoNewline
上述-join
解决方案隐式地将输入对象转换为字符串(如果它们还没有),并通过对每个对象调用.NET.ToString()
方法来实现。这通常会产生与Out File
直接创建的表示不同的表示,因为Out File
使用PowerShell的默认输出格式化程序;例如,比较(Get Date).ToString()
和justGet Date
的输出
如果您的输入仅包含其.ToString()
表示形式令人满意的字符串和/或非字符串,则上述解决方案可以工作,但请注意,通常最好使用Set Content
cmdlet,该cmdlet隐式应用相同的字符串化。有关
输出文件
和设置内容
之间差异的完整讨论,请参阅我的
如果您的输入有非字符串,您希望将其格式化为打印到控制台的格式,那么实际上没有简单的解决方案:虽然您可以使用默认格式设置程序使用
Out String
创建每个对象的字符串表示,但Out String
缺少-NoNewline
(从v5.1开始;建议引入它)总是会产生尾随的新行 要补充briantist和mklement0的有用答案,请参见:
我创建了这个小函数来替换powershell早期版本中Out文件的-NoNewLine参数
注意:在我的例子中,它是一个包含7行的.csv文件(一周中的几天和更多值)
也可以使用append开关来避免覆盖整个文件。例如,“TestTest”| Out file-encoding ascii test.txt-NoNewline-appendWriteAllText总是重写目标文件,因此它对于连续写入日志文件没有用处。
"Test", "Test" -join [Environment]::NewLine |
Out-File -encoding ascii test.txt -NoNewline
## Receive the value we want to add and "yes" or "no" depending on whether we want to
put the value on a new line or not.
function AddValueToLogFile ($value, $NewLine) {
## If the log file exists:
if (Test-path $Config.LogPath) {
## And we don't want to add a new line, the value is concatenated at the end.
if ($NewLine -eq "no") {
$file = Get-Content -Path $Config.LogPath
## If the file has more than one line
if ($file -is [array]) {
$file[-1]+= ";" + $value
}
## if the file only has one line
else {
$file += ";" + $value
}
$file | Out-File -FilePath $Config.LogPath
}
## If we want to insert a new line the append parameter is used.
elseif ($NewLine -eq "yes") {
$value | Out-File -Append -FilePath $Config.LogPath
}
}
## If the log file does not exist it is passed as a value
elseif (!(Test-path $Config.LogPath)) {
$value | Out-File -FilePath $Config.LogPath
}
}