Powershell add-content line breaks

烈酒焚心 提交于 2019-12-01 15:02:17

问题


I am trying to figure out how to eliminate line breaks when using add-content

echo $server "Uptime: " $uptime.days ", Days" $uptime.hours ", Hours" $uptime.minutes ", Minutes" | add-content $output_file

Basically I have been trying to get the uptime of a server to go to a text file, and when I do this the output comes out

HOSTNAME
Uptime:
, 2 Days
2 
, Hours
15
, Minutes

I looked at this question: Powershell replace lose line breaks

Also I went from using out-file -append to add-content, however both produce similar results, can someone shed to some light on how I can eliminate the breaks?


回答1:


I guess you want to have one line with the info, then:

"$server Uptime: $($uptime.days) Days, $($uptime.hours) Hours, $($uptime.minutes) Minutes" | add-content $output_file

If every item should be on separate line, you might add `n

"$server Uptime`n$($uptime.days) Days`n$($uptime.hours) Hours`n$($uptime.minutes) Minutes" | add-content $output_file

Other possibility is to use -f which is sometimes more readable:

"$server Uptime: {0} Days, {1} Hours, {2} Minutes" -f $uptime.days, $uptime.hours, $uptime.minutes | add-content $output_file

Update echo is alias for Write-Output (Get-Alias -name echo) which in your case produces array of objects. This array is passed to Add-Content; each object is stored on its own line.




回答2:


The simplest way to sidestep any problem PowerShell might be putting into the line breaks would be to avoid using the providers.

By using [IO.File]::WriteAllText to write the file, you should be able to avoid the linebreaks that come from PowerShell. The only caveat is that [IO.File]::WriteAllText doesn't understand PowerShell paths, so you'll need to pass it an absolute path.

Hope this helps,




回答3:


how about

[IO.File]::AppendAllText($testfile,"abc",[System.Text.Encoding]::UTF8)


来源:https://stackoverflow.com/questions/5482513/powershell-add-content-line-breaks

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!