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\
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
}
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.
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:
- Right-click on the PowerShell icon.
- Select “Run as administrator.”
- 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 can I create a file using PowerShell?
You can use the New-Item cmdlet to create a file. The following command will create a Word file in the Shared folder:
New-Item -Path '\SharedFolder\newfile.docx' -ItemType File
You can also use the New-Item cmdlet to create folders, directories, and registry keys.
You might want first to check whether the item already exists to avoid an error message.
How do I create a folder in PowerShell?
As mentioned above, you can use the New-Item cmdlet to create a folder. The following command will create a Word file in the Shared folder:
New-Item -Path '\SharedFolder\newfolder.docx' -ItemType File
How do I create a directory using PowerShell?
To create a new directory with PowerShell, use the New-Item cmdlet:
New-Item -Path '\ SharedFolder ' -ItemType Directory
How do I create an empty text file in PowerShell?
You can use the New-Item cmdlet to create a text file PowerShell command. The following command will create a text file in the Shared folder:
New-Item -Path '\SharedFolder\newfile.txt' -ItemType File
How do I create multiple files with different names in PowerShell?
You can use a Loop to Create Multiple Files. Below is an example that will create five files named file1.txt, file2.txt, file3.txt, etc.,
1..5 | ForEach-Object {
New-Item -Path "C:\ C:\NewFolderExample\file$_.txt" -ItemType File
}
How do I add text to a file in PowerShell?
You can use the Add-Content cmdlet to append data to an existing file or create a new file if it doesn’t exist.
Command:
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.
How do I create a PowerShell script file?
You can use the following cmdlet to create a PowerShell script using PowerShell itself.
New-Item -Path "C:\Scripts\MyScript.ps1" -ItemType File
You can even use a text editor such as Notepad. Open Notepad, write your PowerShell code, and save the file with a ps1 extension.
- Open Notepad
- Write your PowerShell code
- Save the file with a .ps1 extension (e.g. script.ps1)
How do I create a ps1 file in PowerShell?
As mentioned above, you can use the New-Item cmdlet mentioned above to create a new file with the .ps1 extension.
New-Item -Path "C:\Scripts\MyScript.ps1" -ItemType File
How do I delete a file using PowerShell?
To delete a file, use the Remove-Item cmdlet:
Remove-Item -Path '\fsSharedNewFolder\newfile.txt'
You will be prompted to confirm the deletion if the file is not empty.
You can also use PowerShell to remove files older than X days or delete files from multiple computers.
How do I force-delete a file using PowerShell?
If you want to delete a file or folder that is read?only or hidden, use the -Force parameter:
Remove-Item -Path '\fsSharedNewFolder\newfile.txt' -Force
How do I copy a file using PowerShell?
Use the Copy-Item cmdlet to copy objects from one location to another:
Copy-Item -Path '\Shared\ITUsers.txt' -Destination '\Backup'
Note that the copy attempt will fail if the target file already exists. Learn how to overwrite the target files during a copy operation.
How do I move a file using PowerShell?
To move an item and its child items (files and folders) from one location to another, use the Move-Item cmdlet:
Move-Item -Path \Shared\Backups1.bak -Destination \Backup
You can also move an entire folder with PowerShell.
How do I rename a file using PowerShell?
To rename a single file using PowerShell, use the following command:
Rename-Item -Path "\Shared\ITUsers.txt" -NewName "IT_Users.txt"
You can also rename multiple files at once using PowerShell.