17

I try to create a folder and a file in one PowerShell command: I tried:

New-Item hello\test\ (New-Item hello\test\file.txt -type file) -type directory -Force

and

New-Item file.txt (New-Item hello\test\ -type direcotry) -type file -Force

But both don't seem to work as expected. What I want to achieve is one command to create hello\test\file.txt

Martin Brandl
  • 56,134
  • 13
  • 133
  • 172
DenCowboy
  • 13,884
  • 38
  • 114
  • 210

4 Answers4

28

Just provide the filepath you want, including the directory, and it will work:

New-Item -Path '.\hello\test\file.txt' -ItemType File -Force
Mark Schultheiss
  • 32,614
  • 12
  • 69
  • 100
Martin Brandl
  • 56,134
  • 13
  • 133
  • 172
1

If you want to put the c.txt file in the b folder of the a folder, do so. ni a/b/c.text -Force

If you want to put two files y.txt and z.hml in x folder ni x/y.txt, x/z.html -Force

0

I created the directory and the file with the following code.

New-Item hello\test -type Directory ; Start-Sleep -Milliseconds 500 ; New-Item   hello\test\file.txt
MahmutKarali
  • 339
  • 4
  • 8
  • Whilst this code snippet is welcome, and may provide some help, it would be [greatly improved if it included an explanation](//meta.stackexchange.com/q/114762) of *how* and *why* this solves the problem. Remember that you are answering the question for readers in the future, not just the person asking now! Please [edit] your answer to add explanation, and give an indication of what limitations and assumptions apply. – Toby Speight Feb 15 '17 at 14:28
  • Your code incorporates three cmdlets (with two relevant to the task.), not one as specified in OP's ask. – Tony Jun 09 '21 at 13:54
0

It's not case-sensitive in powershell command, so the most convenient and fastest way to create file would be - > new-item -path . -name 'newfile.txt' -itemtype 'file'

And for new directory, it's the same as in Linux-terminal -> mkdir newdirectory

tovbaev
  • 1
  • 2