When working with PowerShell, creating multiple files at once can be a convenient way to interact with the file system. In Linux bash, you can use the touch command to create multiple files using a single script line. However, when it comes to PowerShell, things get a bit more complicated.
While there isn’t a direct equivalent to the touch command in PowerShell, we can still achieve the same result using PowerShell. We’ll explore various methods for creating multiple files in PowerShell, including using foreach, variables, and even leveraging WSL (Windows Subsystem for Linux) to run the touch command directly.
We’ll start with a basic example of creating 10 files named file1.txt through file10.txt, and then dive into more advanced examples.
Linux and Touch
In Linux bash, to create multiple files, we can do something like:
touch file{1..10}.txt
The closest equvalent to touch in PowerShell is New-Item.
However, New-Item file{1..10}.txt does not work as expected.
Method 1: Create Multiple Files with foreach
We can create our 10 files using 1..10 to generate integers 1 through 10:
1..10 | foreach { New-Item .\file$_.txt }
or, instead, use strings
'apple', 'banana', 'orange' | foreach { New-Item .\file$_.txt }
⚠️: .\ in the file path other wise you will get the following error:
New-Item: Cannot bind argument to parameter 'Path' because it is null.
How does it work?
1..10generates integers from 1 to 10 inclusive, then pipes it intoforeach.foreachtakes each integer and generates the file name.$_is the current item in the pipe. In this case, it is the integers 1 through 10.
Method 2: Create Multiple Files with foreach (Alternative)
Another alternative would be this, although a bit more difficult to read:
New-Item $(1..10 | foreach { ".\file$_.txt" } )
How does it work?
Along with previous explaination,
$(...)is a cool trick in PowerShell to evaluate what is in the parantheses, which evaluates the snippet inside the paranetheses.
Create Multiple Files using Variables
Using a variable would be useful if the file names are being generated in another part of the script. For this example, using fileNameVar as the variable.
Array of Integers
$fileNameVar = 10,20,30,40
$fileNameVar | foreach { New-Item .\file$_.txt }
Array of Strings
$fileNameVar = 'x','y','abc', 'name with spaces'
$fileNameVar | foreach { New-Item .\file$_.txt }
Create Multiple Files by Specifying Each File
We can also list out the files we want:
New-Item 'first file.txt', 'second_file.txt', 'third-file.txt'
Method 3: Using WSL
We can still use touch through wsl. First, install wsl. Next, we can call wsl from PowerShell and run the command touch:
wsl 'touch' '{1..10}.txt'
This will run wsl and execute the touch command and exit wsl.
Happy Coding! 🪟🐧