"copy con" or "type con > " equivalent in Powershell?
Asked Answered
K

1

16

On Command Prompt, and its syntactical ancestor, DOS, you can create a text file inline by doing this:

copy con file.txt
Hello World
^Z

Or:

type con > file.txt
Hello World
^Z

Is there an equivalent command in Powershell? Neither of the two commands I listed above work.

Kurys answered 23/6, 2017 at 13:46 Comment(6)
cmd /c copy con file.txtBusinesslike
@Businesslike - Yeah, that'd work, but it feels like a cheat. :)Speculate
Even cheatier: notepad file.txt Handy, too, since it shows you the file encoding.Reasonless
I am very interested in your reasons not to use notepad.exe :)Enochenol
@RaúlSalinas-Monteagudo Sometimes it's just a lot easier on my mind to stay focused on one window.Kurys
A side note: If you're trying to paste from the clipboard into a file (which you would do under cmd by copy con file or Linux by cat > file then pasting into the terminal window, you can use Get-Clipboard > file under PowerShell.Epps
W
24

Pipe content to the out-file cmdlet to emulate this.

"Hello World" | out-file hello.txt

To get multiple lines, open the quotes but don't close them right away

"hello
>> is it me you're looking for" | out-file hello2.txt

The >> will appear on the second line after hitting enter

Another way is using "here-strings" for this instead of opening quotes.

@'
hello
is it me you're looking for?
I can even use ' @ $blabla etc in here
and no substitutes will be placed
You want var substitutes, use @"..."@ instead of @'...'@
'@ | out-file hello.txt
Warty answered 23/6, 2017 at 13:55 Comment(6)
Better. Does the output (in hello2.txt) include the newlines?Speculate
@JeffZeitlin yes it doesWarty
Works in the console version, doesn't work in the ISE. Take the point. :)Speculate
As an alternative, use @'<CR> (multiline string) <CR>'@ to feed string data that contains any symbols, including quotes, apostrophes, backslashes and dollar signs. "<CR>" is a newline.Tellez
There seems to be a problem with underscores. They're all eliminated from the result.Bekelja
@Bekelja Try PowerShell 7+.Englis

© 2022 - 2024 — McMap. All rights reserved.