The command for creating a new file on windows using cmd is:
cd.> filename.txt
But how can I create more than one file using a single command?
The command for creating a new file on windows using cmd is:
cd.> filename.txt
But how can I create more than one file using a single command?
With PowerShell you can use New-Item
with an array of filenames.
Note:
ni
is a built-in alias forNew-Item
, which is useful to substitute interactively.
# New-Item
ni fileA.txt, fileB.txt, filec.txt, "file_with_a_${var}_in_it.txt"
You can also use New-Item
to create directories, but a shorter way to do this is to use mkdir
instead, which is a built-in "alias" function for essentially calling New-Item -ItemType Directory
:
# New-Item -ItemType Directory
mkdir dirA, dirB, dirC
If you want to suppress the output, you can pipe or redirect the output. Add | Out-Null
or> $null
to either example above (errors and other streams will still show as written).
Both commands support fully-qualified paths and relative paths. You can provide a single string if you are only creating one item.
You can add as many array elements as you would like, just separate each element in the array with a comma ,
. You can also provide an array variable instead if you need.
here is one way to generate a series of files with powershell. [grin]
the code ...
1..9 |
ForEach-Object {
New-Item -Path $env:TEMP -Name ('FileNumber_{0}.txt' -f $_) -ItemType 'File'
}
what it does ...
New-Item
cmdlet-f
string format operator to build the file nametruncated output ...
Mode LastWriteTime Length Name
---- ------------- ------ ----
-a---- 2022-02-03 1:10 PM 0 FileNumber_1.txt
[*...snip...*]
-a---- 2022-02-03 1:10 PM 0 FileNumber_9.txt
if you want to get rid of the output to the screen, add $Null =
in front of the New-Item
line.