PowerShell – Create a folder if not exists or Create a directory if not exists

In this PowerShell tutorial, we will discuss how to create a folder in PowerShell? Also, we will check how to create a folder if not exists in PowerShell. Or we will check how to create a directory if not exists in PowerShell.

We will see how to use the below PowerShell cmdlets.

  • Test-Path: PowerShell Test-Path cmdlet, we can use to check if a folder exists or not.
  • New-Item: We will use the PowerShell New-Item cmdlet to create a folder in PowerShell.

You can write the below PowerShell script by using visual studio code or PowerShell ISE.

I have also created a video tutorial on PowerShell create directory if not exists.

PowerShell create folder

Now, let us first check how to create a folder in PowerShell. We can use the New-Item PowerShell cmdlet to create a folder.

The below PowerShell command will create a folder with a folder name as of today’s date.

$folderName = (Get-Date).tostring(“dd-MM-yyyy”)
New-Item -itemType Directory -Path E:\Desktop -Name $FolderName

You can see it will create a folder with today’s date like below:

powershell create folder
Create folder using PowerShell

PowerShell create folder if not exists

Now we will check how to create a folder if not exists in PowerShell. The PowerShell command will check if a folder already exists or not. If the folder does not exist then it will create a folder.

PowerShell Provides Test-Path command to check if a folder already exists or not.

$folderName = (Get-Date).tostring("dd-MM-yyyy")
$Path="E:\Desktop\"+$folderName

if (!(Test-Path $Path))
{
New-Item -itemType Directory -Path E:\Desktop -Name $FolderName
}
else
{
write-host "Folder already exists"
}

You can see the below fig since the folder already exists, it will just display the message as Folder already exists.

powershell create directory if not exists
Create folder if not exists using PowerShell

If the folder or directory does not exists, the PowerShell cmd will create directory if not exists.

Read some PowerShell tutorials:

I hope this article will be helpful to create a folder using PowerShell or PowerShell create directory if not exists. Also, we discussed

  • How to create folder if not exists in PowerShell or PowerShell create directory if not exists
  • How do you check if a directory exists or not in PowerShell
  • How to use PowerShell New-Item -itemType Directory
  • Powershell script to create folders and subfolders
  • PowerShell check if directory exists
  • How to use PowerShell Test-Path
>