DEV Community

Cover image for Create Files in PowerShell: New-Item Explained
arnostorg
arnostorg

Posted on

Create Files in PowerShell: New-Item Explained

Create Files in PowerShell: New-Item Explained

Creating files from the command line is faster than using Notepad. Learn the quick way.

How It Works

New-Item creates files when you specify -ItemType File. You can create empty files, or use Out-File to put content inside. This is faster than opening Notepad, typing, and saving.

Code Examples

Create Empty File

# Create empty file
New-Item -ItemType File -Name "notes.txt"

# File is created but empty
# Shortcut:
New-Item -Name "notes.txt"  # Defaults to File
Enter fullscreen mode Exit fullscreen mode

Create File With Content

# Create file AND put text inside in one command
"Hello PowerShell" | Out-File notes.txt

# or use Set-Content
Set-Content -Path notes.txt -Value "Hello PowerShell"
Enter fullscreen mode Exit fullscreen mode

Create Multiple Files at Once

# Create 3 files in one command
New-Item -Name "file1.txt", "file2.txt", "file3.txt"

# All three appear immediately
Enter fullscreen mode Exit fullscreen mode

Create File in Specific Folder

# Create file in Documents folder
New-Item -Name "report.txt" -Path "C:\Users\Documents\"

# or navigate there first
cd Documents
New-Item -Name "report.txt"
Enter fullscreen mode Exit fullscreen mode

Most Used Options

  • -ItemType File - Specify you're creating a file (not folder)
  • -Name 'filename' - Name of the file
  • -Path - Where to create it
  • -Value - Content to put in file

The Trick: Power Usage

Quickly create multiple test files:

# Create 5 empty test files
1..5 | ForEach-Object { New-Item -Name "file$_.txt" }

# Creates: file1.txt, file2.txt, file3.txt, file4.txt, file5.txt
Enter fullscreen mode Exit fullscreen mode

Create file with multi-line content:

@"
Line 1
Line 2
Line 3
"@ | Out-File notes.txt

# Now notes.txt has 3 lines
Enter fullscreen mode Exit fullscreen mode

Learn It Through Practice

Stop reading and start practicing:

👉 Practice on your browser

The interactive environment lets you type these commands and see real results.

Part of PowerShell for Beginners

This is part of the PowerShell for Beginners series:

  1. Getting Started - Your first commands
  2. Command Discovery - Find what exists
  3. Getting Help - Understand commands
  4. Working with Files - Copy, move, delete
  5. Filtering Data - Where-Object and Select-Object
  6. Pipelines - Chain commands together

Related Resources

Summary

You now understand:

  • How this command works
  • The most useful options
  • One powerful trick
  • Where to practice hands-on

Practice these examples until they're automatic. Mastery comes from repetition.


Practice now: Head to the interactive environment and try these commands yourself. That's how PowerShell clicks for you!

What would you like to master next?

Top comments (0)