PowerShell读取文件时保持文本格式

编程入门 行业动态 更新时间:2024-10-27 20:32:20
本文介绍了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读取文件时保持文本格式

本文发布于:2023-10-15 01:29:31,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1492837.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:文本   格式   文件   PowerShell

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!