Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PowerShell keep text formatting when reading in a file

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

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?

like image 208
user1310856 Avatar asked Feb 23 '13 14:02

user1310856


2 Answers

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"
like image 189
Frode F. Avatar answered Nov 07 '22 23:11

Frode F.


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:

Get-Content $file -Raw
like image 26
mjolinor Avatar answered Nov 08 '22 00:11

mjolinor