C# PowerShell 在读入文件时保持文本格式
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15041857/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
PowerShell keep text formatting when reading in a file
提问by user1310856
I believe this is a simple question, but I can't wrap my head around it. I want to do diagnostic commands in command shell on Windows. Like this:
我相信这是一个简单的问题,但我无法解决它。我想在 Windows 上的命令外壳中执行诊断命令。像这样:
$cmd = "ipconfig >> c:\test.txt"
$message = Invoke-Expression($cmd)
[String]$message = Get-Content c:\topsecret\testme.txt
Then I want to be able to read the file and keep the formatting and lastly publish it to pastebin via their API. I've tried, but I seem to lose the formatting no matter what I do. Is this possible to do?
然后我希望能够读取文件并保留格式,最后通过他们的 API 将其发布到 pastebin。我试过了,但无论我做什么,我似乎都丢失了格式。这是可能的吗?
采纳答案by Frode F.
This happens because of your casting. Get-Content
returns an object array with a string object per line in the textfile. When you cast it to [string]
, it joins the objects in the array. The problem is that you don't specify what to join the objects with (e.g. linebreak (backtick)n
).
这是因为你的铸造。Get-Content
返回一个对象数组,文本文件中每行一个字符串对象。当您将其转换为 时[string]
,它将连接数组中的对象。问题是你没有指定用什么来连接对象(例如 linebreak (backtick)n
)。
ipconfig >> test.txt
#Get array of strings. One per line in textfile
$message = Get-Content test.txt
#Get one string-object with linebreaks
$message = (Get-Content test.txt) -join "`n"
回答by David Brabant
Cast to an array of strings, maybe. Like this, for your last example:
可能转换为字符串数组。像这样,对于你的最后一个例子:
$message = @(Get-Content c:\topsecret\testme.txt)
Or this for the second one:
或者这是第二个:
$message = [string[]](ipconfig)
回答by mjolinor
To read all the data as a single string with the line breaks embedded
将所有数据作为嵌入换行符的单个字符串读取
$file = 'c:\testfiles\testfile.txt'
(IPconfig /all) > $file
[IO.File]::ReadAllText($file)
If you have V3, they added the -Raw parameter that will accomplish the same thing:
如果你有 V3,他们添加了 -Raw 参数来完成同样的事情:
Get-Content $file -Raw