简体   繁体   中英

How can I create multiple files using a single command on windows command line?

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?

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...

  • generates a number range
  • pipes each number to the New-Item cmdlet
  • uses the -f string format operator to build the file name
  • creates the file

truncated 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.

With PowerShell you can use New-Item with an array of filenames.

Note: ni is a built-in alias for New-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

Some tips

  • If you want to suppress the output, you can pipe or redirect the output. Add | Out-Null | 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM