Using PowerShell – Create a folder if not exists

No comments

In this post I will show how to create a folder or directory if not exists in the given directory or path using PowerShell code or script.

The below PowerShell code will create a folder with the name “LogFiles” in the .ps1 file root directory if not exists.

Create a folder in the Powershell .ps1 file directory if folder not exists.

cls
$fileName = "File_Uploading_Report"
#'yyyyMMddhhmm   yyyyMMdd
$enddate = (Get-Date).tostring("yyyyMMddhhmmss")
#$filename =  $enddate + '_VMReport.doc'  
$logFileName = $fileName +"_"+ $enddate+"_Log.txt"   
$invocation = (Get-Variable MyInvocation).Value  
$directoryPath = Split-Path $invocation.MyCommand.Path  

$directoryPathForLog=$directoryPath+"\"+"LogFiles"
if(!(Test-Path -path $directoryPathForLog))  
{  
 New-Item -ItemType directory -Path $directoryPathForLog
 Write-Host "Folder path has been created successfully at: " $directoryPathForLog    
 }
else 
{ 
Write-Host "The given folder path $directoryPathForLog already exists"; 
}


Folder creation example in the Powershell .ps1 file directory:

CreateFolderIfNotExistsPowerShell

Create a folder in the given directory if folder or directory not exists.

Using the below code we can create a folder in a given path or directory if folder not exists. 

cls
$directoyPath="C:\Temp\CreateFolderIfNotExists\Sample Path\Test Folder";
if(!(Test-Path -path $directoyPath))  
{  
    New-Item -ItemType directory -Path $directoyPath
    Write-Host "Folder path has been created successfully at: " $directoyPath
               
}
else
{
Write-Host "The given folder path $directoyPath already exists";
}

Create a folder in the given directory if folder or directory not exists – Example:

CreateFolderIfNotExistsPowerShell2

Summary:

Thus, in this post we have explored the below:

  • Create a Folder If Not Exists in PowerShell.
  • Create directory if it does not exist.
  • New-Item – Create Folders & Files using PowerShell Basics.
  • PowerShell script to validate if a folder exists – creates it if not.
  • Test-Path – Folder Creation in PowerShell.
  • Using PowerShell check and create a folder if it doesn’t exists.