Command Prompt to PowerShell
To create a new text file using PowerShell, use New-Item
. Classically, done by echo "some text" > into-a-file.txt
, but PowerShell New-Item
provides more robustness.
The equvalent of the echo
redirect >
to a new file is PowerShell cmdlet New-Item
. In this example, output hello
into a new text file in the current directory called myFile.txt
.
echo hello > myFile.txt
New-Item ".\myFile.txt" -Value "hello" -Force
Note that New-Item
does not replace the file if it already exists by default, we can use -Force
to emulate the behavior of the echo redirect. If you run the command without -Force
it will give error: New-Item: The file 'C:\myFile.txt' already exists.
Create a empty new file
New-Item -Path ".\myFile.txt"
or more simply, by dropping -Path
:
New-Item myFile.txt -Force
or if you want to overwrite your previous file if already created, add -Force
:
New-Item -Path ".\myFile.txt" -Force
Create a new file with contents
New-Item -Path ".\myFile.txt" -Value "hello"
Or if you have a variable you want to output:
New-Item -Path .\myFile.txt -Value "$(Write-Output $PsVersionTable.PSVersion)"
Create a new file (split the path and file name)
The Path
and file name can be split into Name
New-Item -Path . -Name "myFile.txt" -Value "hello world"
Create multiple files
To create multiple files at once, we can pass multiple paths deliminated by ,
.
New-Item -ItemType "file" -Path ".\a.txt", ".\b.txt"
# or more simply
New-Item -ItemType "file" ".\a.txt", ".\b.txt"
# or more simply
New-Item ".\a.txt", ".\b.txt"
Create a directory
We can use -ItemType
to specify we want to create a new directory
New-Item -Path "." -Name "myCoolDirectory" -ItemType "directory"
# or simply:
New-Item ".\myCoolDirectory" -ItemType "directory"
Create multiple directories
We can apply the same string array to the Path parameter and create mutliple directories.
New-Item -ItemType "directory" -Path ".\dog",".\cat",".\fish"
# or simply:
New-Item -ItemType "directory" ".\dog",".\cat",".\fish"