Create Folder If Not Exist in PowerShell

This tutorial will explain how to create a folder using PowerShell if it does not exist in the given location.

Using Test-Path and New-Item Cmdlets

To create folder if not exist in PowerShell:

  • Use Test-Path cmdlet with if statement to check the path.
  • If folder doesn’t exist, Create a new folder with New-Item cmdlet.

Output:

First, we assigned the folder path to the $path variable. Then we used Test-Path to determine whether the folder exists in that location. It checks whether all elements in the path exist.

If the path exists, the statement is True, and the first command gets executed. It prints the message Folder already exists.

If the path does not exist, New-Item creates a directory New Folder in the C:\test directory. At last, the Write-Host outputs the message Folder created successfully.

New-Item is cmdlet which is used to create new item. In this example, we created new folder with the help of New-Item cmdlet.

Using Directory.Exists() Method

To check if a folder exists in the given path, use [System.IO.Directory]::Exists() method.

Output:

The .NET class’s [System.IO.Directory]::Exists() method is used as the conditional test in the if statement. It evaluates to True if the path exists and False if it does not. If the return value is False, New-Item creates a new folder in the specified path.

Using Get-Item with New-Item Cmdlet

To create a folder if it does not exist:

  • Use Get-Item to check the path.
  • Use New-Item to create a folder.

Output:

In the above example,

  • $path contains the folder name and path.
  • Get-Item checks if the folder exists in the path.
  • New-Item creates a new folder if it does not exist in the given location.
  • -ErrorAction Ignore hides the exception raised by Get-Item when the path is not found.

That’s it. Now you should know how to create folder if not exists in PowerShell. If you have any confusion, let us know in the comments.

Was this post helpful?

Leave a Reply

Your email address will not be published. Required fields are marked *