This blog will observe the demonstration of the “New-Item” cmdlet.
How to Use the “New-Item” Command in PowerShell?
As stated earlier, the “New-Item” cmdlet gives birth to new items, such as files or folders. The examples are provided below to explain the functions of the stated cmdlet.
Example 1: Use the “New-Item” Cmdlet to Create a New Directory
This example will create a directory in PowerShell using the “New-Item” cmdlet:
According to the above code:
- First, add the “New-Item” cmdlet followed by the directory address to create a new directory inside it.
- Then, add the “-Name” parameter to name the directory new directory to be created.
- Lastly, create a “-ItemType” parameter and define “directory” to it:
Example 2: Use the “New-Item” to Create a File in the Desired Directory
This example will demonstrate to create a new file inside the respective folder path provided by the user:
According to the above code:
- First, add the “New-Item” cmdlet, specify the “-ItemType” parameter and assign the “file” value.
- After that, define the “-Path” parameter and assign the file address to create a file.
- The file name is also added at the end of the file path along with the file extension:
Example 3: Use the “New-Item” Cmdlet Along With the “-Force” Parameter to Overwrite an Existing File
The following example will overwrite an existing file with the aid of the “-Force” parameter:
In the above-stated code, just add the “-Force” parameter to overwrite the existing file.
Example 4: Use the “New-Item” Cmdlet to Create a File in the Present Directory
This following demonstration will generate a file in the current working directory:
According to the above code:
- After adding the “New-Item” cmdlet, specify the “-Name” parameter and define the file name within double quotes.
- Then, add the “-ItemType” parameter.
- Add the “-Value” parameter and specify the value within double quotes to save inside the file:
Example 5: Use the “New-Item” Cmdlet to Create a Directory in the Desired Path
Now, generate a new folder inside the desired directory:
In the above-stated code, the “-Path” parameter is added to add the directory path where the user wants to create a new folder inside it:
Example 6: Use the “New-Item” Cmdlet to Create Multiple Files
This example will create multiple files at once using the “New-Item” cmdlet. To do so, simply add the path of multiple files to the “-Path” parameter separated by a comma:
That was all about using the New-Item cmdlet in PowerShell.
Conclusion
The “New-Item” cmdlet in PowerShell helps create new files and folders. Moreover, with the aid of several parameters, it can create multiple files or folders at once. This write-up has elaborated on several demonstrations of the “New-Item” cmdlet in PowerShell.