PowerShell读取文件时保持文本格式 [英] PowerShell keep text formatting when reading in a file

查看:77
本文介绍了PowerShell读取文件时保持文本格式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我相信这是一个简单的问题,但是我无法解决这个问题.我想在Windows的命令外壳中执行诊断命令.像这样:

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:

   $cmd =  "ipconfig >> c:\test.txt"

   $message = Invoke-Expression($cmd)

   [String]$message = Get-Content c:\topsecret\testme.txt

然后,我希望能够读取文件并保留格式,最后通过其API将其发布到pastebin.我已经尝试过了,但是无论我做什么,我似乎都失去了格式设置.这可能吗?

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?

推荐答案

发生这种情况是由于您的转换. Get-Content 返回一个对象数组,该对象数组在文本文件中每行包含一个字符串对象.当将其强制转换为 [string] 时,它将连接数组中的对象.问题在于您不指定将对象与对象连接的对象(例如,换行符(backtick)n ).

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).

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"

这篇关于PowerShell读取文件时保持文本格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆