19

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

4 Answers 4

31

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

New-Item -Path '.\hello\test\file.txt' -ItemType File -Force
Sign up to request clarification or add additional context in comments.

7 Comments

Oh god, you're right. Will accept it in some minutes.
I have to specifty the file type (PowerShell ISE v4). New-Item -Path '.\hello\test\file.txt' -Force -ItemType File
Yep me to, but wasn't that relevant for the question so I'll accept it. Thanks @TechSpud. Maybe edit the answer
I tried this in PowerShell 7.4.5 (runas admin) and it produces the error New-Item: Could not find a part of the path 'c:\some\path\where\some\folder\does\not\exist\filename'. Any idea why it does not work? Note that only the last folder corresponding to exist did not exist.
@GoWiser Hm, have you added the -Force switch?
|
2

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

Comments

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

2 Comments

Whilst this code snippet is welcome, and may provide some help, it would be greatly improved if it included an explanation 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.
Your code incorporates three cmdlets (with two relevant to the task.), not one as specified in OP's ask.
-1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.