How to Check a directory exists and create the folder if it does not exists using Powershell

We can use the If condition, Test-Path and New-Item to check and create a directory if it does not exists

Syntax:  if(!(Test-Path -Path <Complete Path>))
        {
          New-Item -ItemType directory -Path <Complete Path>
        }

Example:
if(!(Test-Path -Path C:\Development ))
{
New-Item -ItemType directory -Path C:\Development
}
Above Example using Variables -
$TargetDir = 'C:\Development'

if(!(Test-Path -Path $TargetDir ))
{
New-Item -ItemType directory -Path $TargetDir
}
Here the variable TargetDir holds the directory including the path.

Related Posts

1) How to create a folder or sub directory using Windows PowerShell
http://pnsoftwarestudies.blogspot.com/2015/11/how-to-create-folder-or-sub-directory.html

No comments: