logo

PowerShell Create File: Step-by-Step Guide

System administrators perform a variety of standard operations on their Windows servers every day, including creating, deleting, and moving files and folders. By becoming fluent with the core set of Active Directory (AD) PowerShell commands provided in this blog post, you can dramatically reduce the manual work involved to create a file in PowerShell.

Before you start, ensure your system policy allows running PowerShell scripts, as described in “Windows PowerShell Scripting Tutorial for Beginners.” In the article below, you will learn the PowerShell command to create a file, delete it, copy it, and append content to it.

Basic File Creation with New-Item Cmdlet

Use the PowerShell cmdlet New-Item to create an object, such as a directory, file, or registry key. The -Path parameter specifies the location where the new item will be made, and the -ItemType parameter specifies the type of item to create. Additional parameters, such as -Name and -Value, can be used to specify the name of the new item and its content. Now, let’s show you how to create a file in PowerShell.

Step-by-step guide: Creating empty files and folders

Create a folder

New-Item -Path “c:\NewFolderExample” -ItemType Directory

Below is an example using the PowerShell create file command:

Create a file

Next, we will cover how to make a file in PowerShell, as seen below:

New-Item -Path ”c:\NewFolderExample\newfile.txt” -ItemType File

Explanation of Parameters

Let’s look at the code components of the New-Item cmdlet:

  • -Path: This parameter specifies where the new file will be created. In the example above, the file was created in the newly created folder. You can change this path to any directory where you want the file to be created.
  • -ItemType: This parameter defines the type of item to create. In the examples above, we specified Directory and File.

In PowerShell, an item path refers to the location of an item (such as a file or directory) within the file system or other provider namespaces. In the example above, we used a fully qualified item path, which included all elements (provider, drive, containers, item name). You can also use relative paths. In a relative path, the backslash at the beginning doesn’t refer to the root of the drive. Instead, it is treated as part of the folder name. The actual location depends on your current working directory in PowerShell. Below, we show how to create a text file in PowerShell using a relative file path:

New-Item -Path '\NewExampleFolder\newfile.txt' -ItemType File

Examples

Creating files in different directories

You can make a file in PowerShell within various directories by changing the -Path parameter. For example:

New-Item -Path "c:\projects\myfile.txt" -ItemType File

This create file PowerShell command creates an empty file named myfile.txt in the D:\projects directory.

Creating files with specific extensions

You can use the create file Windows PowerShell command to generate files with specific extensions. For example:

New-Item -Path "c:\NewFolderExample\mydocument.docx" -ItemType File

This command creates an empty file named mydocument.docx in the c:\NewFolderExample directory. You can specify any file extension, such as .docx, .txt, or .csv, depending on the type of file you want to create.

Adding Content to Files

Using Set Content

The Set Content cmdlet in PowerShell is used to write or replace the content of a file. This cmdlet is useful when creating or overwriting text in a file with specific content. The command Set-Content is ideal for writing simple text to a file and can be used with automated scripts to generate configuration files or logs with predefined content. It directly replaces the file’s content without appending. powershell create file with content.

Set-Content -Path "c:\NewFolderExample\greetings.txt" -Value "Hello, World!"

Using Out-File

You can also create a file and write data using the Out-File cmdlet, as shown below:

Get-Process -Name * | Out-File -FilePath c:\ NewFolderExample \processes.txt

Another option is to pipe the output from a cmdlet, such as Get -ADuser, to Export-Csv, which creates a file that can be opened in Excel:

Get-ADuser -Filter * | Export-Csv -Path c:\dataADusers.csv

Out-File is commonly used to capture the output of commands, such as Get-Process, and save it to a file. This is useful for logging and reporting purposes. Out-File is better suited for handling large amounts of output than the Set-Content cmdlet, as it streams data to the file rather than loading it into memory first. Unlike Set-Content, Out-File can append to an existing file with the -Append option.

View the objects in a directory

To view the contents of a directory on a Windows file server, including all files and subdirectories, use the Get-ChildItem cmdlet. The output includes each item’s name, size, and last modified date. It is similar to the dir or ls command in Windows.

Get-ChildItem -Path C:\NewFolderExample\

Show hidden objects

The command below shows all root objects, including hidden ones, in the NewFolderExample folder:

Get-ChildItem -Path "c:\NewFolderExample -Force

Show all subfolders and their content

The following command uses the -Recurse parameter to extend the output to include all subfolders and their content. Each subfolder will be displayed separately. For example:

Get-ChildItem -Force \ NewFolderExample -Recurse

The example below shows the contents of a second folder inside of NewFolderExample.

Filter the output

You can filter the output using the -Filter-Exclude-Include and -Path parameters.

For advanced object filtering, use the pipe operator (|) to pass data from the Get ChildItem cmdlet to the Where-Object cmdlet. For instance, the script below searches for all executable files in the fsShared folder and subfolder modified after 18 July, 2024.

Get-ChildItem -Path C:\NewFolderExample -Recurse -Include *.csv | Where-Object -FilterScript {($_.LastWriteTime -gt '20

Advanced File Creation Techniques

Creating multiple files

Creating multiple files efficiently in PowerShell can be achieved using loops. This method is beneficial when creating files with similar names or in different directories.

Using a loop to create multiple files

Here’s an example of using a loop to create multiple files:

1..5 | ForEach-Object {

    New-Item -Path "C:\ C:\NewFolderExample\file$_.txt" -ItemType File

}

Explanation of Parameters:

  • 1..5: This creates a range of numbers from 1 to 5.
  • ForEach-Object: This cmdlet iterates through each number in the range.
  • New-Item: This cmdlet creates a new file for each iteration inside the loop.
  • -Path “C:\temp\file$_.txt”: The path where each file will be created. $_ represents the current number in the iteration.

This script will create five files named file1.txt, file2.txt, file3.txt, etc., as shown below:

You can use loops to do things such as create a template file in multiple project directories, initialize log files in various application directories, or distribute a default configuration file to multiple user directories.

Using Wildcards

You can use wildcards in PowerShell to perform operations on multiple files or directories simultaneously. Wildcards can create files across multiple directories in a single command when used with the New-Item cmdlet:

New-Item -Path " C:\NewFolderExample\*\example.txt" -ItemType File

Explanation of Parameters:

  • This command attempts to create a file named example.txt in all immediate subdirectories of C:\temp.
  • The * in the path acts as a wildcard, matching any directory name.
  • PowerShell will iterate through all subdirectories in C:\temp and create example.txt in each one.
  • If example.txt already exists in a subdirectory, it will not be overwritten unless you add the -Force parameter.

Delete Files and Folders

Thus far, we have focused on creating files, but you can also use PowerShell to delete files. Use the Remove-Item PowerShell cmdlet to delete a file, directory, or other object. For example, the following command will delete the specified folder and all the subfolders and files. Notice that because the folder is not empty, you are prompted to confirm the operation:

Remove-Item -Path '\NewFolderExample’

If you have already made sure that every object inside the folder should be deleted, you can use the -Recurse switch to skip the confirmation step:

Remove-Item -Path '\NewFolderExample' -Recurse

Delete a file

The following command will delete the file named newfile.txt from the folder NewFolderExample:

Remove-Item -Path “C:\NewFolderExample\newfile.txt”

Delete files older than x days

To clean up old files from a directory, use a script like this:

Get-ChildItem -Path "C:\ NewFolderExample " -Recurse | Where-Object {($_.LastWriteTime -lt (Get-Date).AddDays(-30))} | Remove-Item

Delete empty folders

The following script will identify empty folders and delete them without prompting for confirmation:

$Folder = "C:\ NewFolderExample "

#Delete empty folders and subfolders

Get-ChildItem $Folder -Recurse -Force -ea 0 |

? {$_.PsIsContainer -eq $True} |

? {$_.getfiles().count -eq 0} |

ForEach-Object {

    $_ | del -Force -Recurse

    $_.FullName | Out-File C:\deletedfolders.txt -Append

}

Delete files after checking they exist

Here’s how to check whether a file called datalog.txt exists and delete it if it does:

$FileName = 'C:\datalog.txt'

If (Test-Path $FileName){

   Remove-Item $FileName

}

Monitor File Management Activities with Netwrix Change Tracker

Tracking file changes manually can be a challenge. Let Netwrix help!

We care about security of your data.

Privacy Policy

Overwriting and Appending to Files

Earlier, we discussed using the Set-Content cmdlet to write or replace a file. Here are some other ways to do the same.

Using -Force Parameter

Here is another PowerShell create file command parameter to overwrite existing content:

New-Item -Path "C:\NewFolderExample\example.txt" -ItemType File -Force

The -Force parameter in PowerShell is used to override restrictions that prevent you from making changes, such as read-only attributes or the existence of an item with the same name. This command adds “Additional line” to the end of “example.txt”. If the file doesn’t exist, it creates it.

Before running the command, note the size of the example.txt file below:

Now see how using the Windows PowerShell create file cmdlet with the -Force parameter wipes out the prior content.

Explanation of Parameters:

  • If “example.txt” already exists, this command will overwrite it without prompting.
  • If the file is read-only, -Force will override this attribute and replace the file.
  • It’s useful for scripts where you want to ensure a fresh file is created each time, regardless of existing content

Appending Content

You can use the Add-Content cmdlet to append data to an existing file or create a new file if it doesn’t exist. For example:

Add-Content -Path "C:\temp\example.txt" -Value "Additional line"

This command adds “Additional line” to the end of “example.txt”. If the file doesn’t exist, it creates it.

Comparison with Set-Content and Out-File:

Key Differences:

  • Add-Content is for appending, Set-Content is for replacing, and Out-File is for flexible output redirection.
  • Add-Content preserves and adds, Set-Content replaces, and Out-File can do either.

Creating Special File Types

CSV Files

CSV (Comma-Separated Values) files are widely used for storing tabular data. The PowerShell Export-CSV cmdlet lets you create and manipulate CSV files. It converts objects into a series of comma-separated value (CSV) strings and saves them in a CSV file, as seen below:

$data | Export-CSV -Path "C:\ NewFolderExample\data.csv" -NoTypeInformation

In the example below, $data is a variable that contains objects you want to export:

Explanation of Parameters:

  • -NoTypeInformation: Omits the type of information from the CSV file. This often creates cleaner CSV files without the PowerShell-specific type data.
  • Export-CSV: This cmdlet converts the objects to CSV format.

JSON Files

JSON (JavaScript Object Notation) files are text files that store data in a structured, easy-to-read format. In PowerShell, JSON files are often used to store configuration data, application settings, or other data represented as key-value pairs.

The combination of ConvertTo-Json and Out-File allows you to convert PowerShell objects to JSON format and save them to a file.

$data | ConvertTo-Json | Out-File -FilePath "C:\NewFolderExample\data.json"

Some uses for using JSON files with PowerShell include exporting configuration data from a PowerShell script for use in a web application, creating a settings file for a PowerShell-based application, or Preparing data to send to a RESTful API or storing API responses.

Windows PowerShell Scripting Tutorial for Beginners

We care about security of your data.

Privacy Policy

Handling Existing Files

When working with files in PowerShell, you may want to see if a file exists before performing operations to prevent possible errors.

Checking if the file exists

The Test-Path cmdlet is commonly used to check for the existence of files or directories. Here’s how to check whether a file called datalog.txt exists and delete it if it does:

$FileName = 'C:\datalog.txt'

If (Test-Path $FileName){

   Remove-Item $FileName

}

Conditional File Creation

You can add a condition to a file creation command. For example, the command below checks to see if the datalog.txt file exists, and if not, will create one automatically.

If (-not(Test-Path -Path "C:\temp\example.txt")) {

    New-Item -Path "C:\temp\example.txt" -ItemType File

}

Explanation of parameters:

  • Test-Path -Path “C:\temp\example.txt”: Checks if the file exists.
  • -not: Negates the result, so the condition is proper if the file does not exist.
  • If the file doesn’t exist, New-Item creates it.

In the example below, newfile.txt will only be created if the ‘NewFolderExample’ directory exists

If (Test-Path -Path "C:\NewFolderExample") {

    New-Item -Path "'C:\NewFolderExample \newfile.txt" -ItemType File

} else {

    Write-Warning "Directory C:\ ''C:\NewFolderExample does not exist"

}

An applicable use case would be creating a default config file only if it doesn’t exist, avoiding overwriting existing customized configurations.

Copy and Manipulating Files and Folders

Copy files and folders

If you’re looking copy items, such as files and directories, from one location to another, use the Copy-Item PowerShell cmdlet. It is similar to issuing the copy command from the Windows command prompt.

To copy a file between two folders on the same computer, use this command:

Copy-Item -Path '\Shared\ITUsers.txt' -Destination '\Backup'

Copy only certain types of files

Use the -Filter parameter to copy only certain files from the source to the destination. For instance, the following command copies only text files from one folder to another:

Copy-Item -Filter *.txt -Path \Shared\* -Recurse -Destination \Backup

Rename a file or folder

The Rename-Item cmdlet enables you to change the name of an object, such as a file or directory, while leaving its contents intact. It is similar to the Windows command ren.

The -Path parameter specifies the location of the file or directory, and the –NewName parameter provides the new name of the file or folder.

For example, the following PowerShell create text file command renames a text file to a similar name with an underscore character added:

Rename-Item -Path "\Shared\ITUsers.txt" -NewName "IT_Users.txt"

Change file extensions

You can also use Rename-Item to change file extensions.

If you want to change the extensions of multiple files at once, use the following PowerShell change file extension, which will change all txt file extensions to bak. The wildcard character (*) ensures that all text files are included.

Get-ChildItem \Shared\*.txt | Rename-Item -NewName { $_.name -Replace '.txt','.bak' }

Troubleshooting Common Issues

Permission issues

Insufficient privileges are a common problem when you’re working with PowerShell. A typical error message is “The process does not have access rights to this object.” The solutions to this issue are:

  • Run PowerShell as an administrator for system-level operations.
  • Modify ACLs (Access Control Lists) to grant necessary permissions.
  • Use alternate credentials

To run PowerShell with elevated privileges:

  1. Right-click on the PowerShell icon.
  2. Select “Run as administrator.”
  3. Confirm the User Account Control prompt.

Typing errors

It is easy to misspell parameter names, but doing so will result in an error. When typing long commands, you can use tab completion or check cmdlet help (Get-Help cmdlet-name -Detailed).

File already exists

Depending on what you are trying to do, an existing file name may cause an error. One way to avoid this is to use a conditional command, as was covered earlier.

If (-not(Test-Path -Path "C:\temp\example.txt")) {

    New-Item -Path "C:\temp\example.txt" -ItemType File

}

Real World Applications

Scripting Examples

You can use PowerShell to create log files. Logging is essential for tracking system activities, errors, and application behavior. PowerShell can automate the creation of log files, making it easier to monitor systems. The example below shows a function that allows you to easily log messages with timestamps, which is necessary for auditing. We then used the Get-ChildItem cmdlet to confirm the log file’s creation.

You can use PowerShell to create scripts to automate and streamline various tasks. For example, you can create scripts to backup files, check for available disk space on a server, or monitor critical system services.

Using Visual Studio Code

You can empower PowerShell with Visual Studio Code (VS Code). VS Code is a versatile code editor that provides an excellent environment for PowerShell scripting and development. Install VS Code and the PowerShell extension to gain access to features like syntax highlighting, IntelliSense for cmdlets and variables, code snippets, and integrated debugging. The editor offers a customizable interface with an integrated terminal, allowing you to seamlessly write, test, and run PowerShell scripts.

Installing Visual Studio Code

  • Download and install Visual Studio Code from the official website: Visual Studio Code.
  • Once installed, open VS Code and navigate to the Extensions view by clicking on the square icon on the sidebar or pressing Ctrl+Shift+X.
  • Search for the “PowerShell” extension in the Extensions view and click “Install”. This extension provides rich PowerShell language support, including syntax highlighting, IntelliSense, code navigation, and debugging.

Conclusion

PowerShell is a powerful tool for file and system management. It offers various cmdlets and techniques for creating, modifying, and managing files and directories. You can use the New-Item cmdlet to create essential files. You can then use more advanced scripts to create multiple files, search for existing ones, and move or delete them. You can also use PowerShell scripts to automate mundane tasks and free up time for your IT personnel. Because PowerShell is widely used today, a wealth of resources are available online to help guide you in your learning and exploration.

FAQ

How to fix PowerShell permission denied when creating files?

PowerShell permission denied errors occur when the execution policy blocks file operations or when you lack write permissions to the target directory. First, check your execution policy:

Get-ExecutionPolicy

Set it to RemoteSigned or Unrestricted if needed:

Set-ExecutionPolicy RemoteSigned

For directory permission issues, run PowerShell as Administrator or create files in directories where you have write access like your user profile folder. Use Test-Path to verify directory existence before creating files:

if (Test-Path "C:\MyFolder") {
    New-Item -Path "C:\MyFolder\file.txt" -ItemType File
}

Implement proper error handling with try-catch blocks to manage permission failures gracefully. When working with system directories, consider using alternate locations or requesting elevated privileges. For enterprise environments, ensure your script accounts have appropriate permissions and follow least privilege principles when granting file creation access. Remember that permission issues often reflect security policies designed to protect system integrity.

What are the different methods to create files in PowerShell?

PowerShell offers several file creation methods, each optimized for different scenarios:

# Create empty files
New-Item -Path "file.txt" -ItemType File

# Redirect command output to files  
Get-Process | Out-File "processes.txt"

# Write data to files
Set-Content -Path "data.txt" -Value "Hello World"

# Append data to files
Add-Content -Path "log.txt" -Value "New entry"

# .NET method for performance-critical operations
[System.IO.File]::WriteAllText("C:\file.txt", "Content")

Export-CSV creates structured data files from PowerShell objects. Each method has specific use cases – New-Item for file system operations, Out-File for command output capture, Set-Content for data replacement, and Add-Content for logging scenarios. Choose the method that best matches your specific file creation requirements and data handling needs.

How to create files in PowerShell with proper error handling?

Proper error handling in PowerShell file creation prevents script failures and provides meaningful feedback when operations fail. Wrap file creation commands in try-catch blocks:

try {
    New-Item -Path "C:\MyFolder\file.txt" -ItemType File -ErrorAction Stop
    Write-Host "File created successfully"
} catch {
    Write-Error "Failed to create file: $($_.Exception.Message)"
}

Verify directory existence and create missing directories:

if (-not (Test-Path "C:\MyFolder")) {
    New-Item -ItemType Directory -Path "C:\MyFolder" -Force
}

Implement specific error handling for common issues like permission denied, file already exists, or disk space limitations. Include logging mechanisms that capture both successful operations and failures for audit purposes. Use Write-Error for non-terminating errors and throw for critical failures that should stop script execution. Validate input parameters before attempting file operations and provide clear error messages that help users understand what went wrong. For production scripts, consider implementing retry logic for transient failures and comprehensive logging for compliance and troubleshooting purposes.

How to create PowerShell files with secure permissions?

Creating files with secure permissions requires setting appropriate access controls during or immediately after file creation. Create the file and apply security settings:

# Create file
New-Item -Path "C:\secure-file.txt" -ItemType File

# Get current ACL
$acl = Get-Acl "C:\secure-file.txt"

# Modify permissions
$accessRule = New-Object System.Security.AccessControl.FileSystemAccessRule("Domain\User", "FullControl", "Allow")
$acl.SetAccessRule($accessRule)

# Apply ACL
Set-Acl -Path "C:\secure-file.txt" -AclObject $acl

For sensitive files, explicitly remove inherited permissions and grant access only to specific users or groups that require it. Consider using PowerShell’s security cmdlets to implement least privilege access, ensuring files are readable only by authorized personnel. When creating temporary files, place them in secure locations with restricted access and implement cleanup procedures to remove them after use. For compliance-sensitive environments, include audit settings in your access control lists to track file access attempts. Remember that file security starts with understanding who needs access to what data and implementing controls that enforce those requirements while maintaining usability.

PowerShell file creation fails – what are common causes and solutions?

PowerShell file creation failures typically stem from permission issues, invalid paths, or execution policy restrictions. Check that the target directory exists and create it if necessary:

if (-not (Test-Path "C:\TargetFolder")) {
    New-Item -ItemType Directory -Path "C:\TargetFolder"
}

Verify you have write permissions to the destination folder and run PowerShell as Administrator if working with system directories. Ensure file paths don’t contain invalid characters such as pipes, question marks, or quotation marks that Windows doesn’t support in filenames. Check available disk space, as full drives prevent file creation. Review your PowerShell execution policy:

Get-ExecutionPolicy
# Adjust if needed
Set-ExecutionPolicy RemoteSigned -Scope CurrentUser

For network paths, verify connectivity and authentication before attempting file creation. Use specific error handling to identify whether failures are due to permissions, paths, or system resources. When troubleshooting, test with simple file creation commands first, then gradually add complexity to isolate the specific cause of failures.

Kevin Horvatin is a Lead Software Architect at Netwrix and responsible for Netwrix Privilege Secure. A software developer for over 20 years, he has worked with PowerShell and C# since they were introduced. 
Automate Active Directory Groups & User Management