Create a File If Not Exists via PowerShell

We can check if a file exists or not by using the PowerShell cmdlet Test-Path and create a new file using the New-Item cmdlet.

The below PowerShell script checks whether the file “sample.txt” already exists or not under the path “C:\Share\”. It creates a new file if it does not exist already and adds new text content by using the Add-Content cmdlet if the file already exists.

if (!(Test-Path "C:\Share\sample.txt"))
{
   New-Item -path "C:\Share" -name "sample.txt" -type "file" -value "first text content"
   Write-Host "Created new file and text content added"
} else {
  Add-Content -path "C:\Share\sample.txt" -value "new text content"
  Write-Host "File already exists and new text content added"
}

By default, the New-Item cmdlet just creates the file, the folder path should have been already created. You will get the following error message If the folder (Ex: “C:\Share”) doesn’t already exist.

New-Item : Could not find a part of the path ‘C:\Share\sample.txt’.

We need to use the –Force parameter to create a file along with the directory if not available. The following command creates the file “sample.txt” and the folder “C:\Share” (if not exist).

New-Item -path "C:\Share" -name "sample.txt" -type "file" -value "text content" -Force
Advertisement

3 thoughts on “Create a File If Not Exists via PowerShell”

Leave a Comment