Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create directory if it does not exist

I am writing a PowerShell script to create several directories if they do not exist.

The filesystem looks similar to this

D:\ D:\TopDirec\SubDirec\Project1\Revision1\Reports\ D:\TopDirec\SubDirec\Project2\Revision1\ D:\TopDirec\SubDirec\Project3\Revision1\ 
  • Each project folder has multiple revisions.
  • Each revision folder needs a Reports folder.
  • Some of the "revisions" folders already contain a Reports folder; however, most do not.

I need to write a script that runs daily to create these folders for each directory.

I am able to write the script to create a folder, but creating several folders is problematic.

like image 464
ecollis6 Avatar asked Jun 03 '13 21:06

ecollis6


People also ask

How do you create directory in Python if it does not exist?

import os path = '/Users/krunal/Desktop/code/database' os. makedirs(path, exist_ok=False) print("The new directory is created!") So that's how you easily create directories and subdirectories in Python with makedirs(). That's it for creating a directory if not exist in Python.

How do you create a directory if it does not exist in Java?

Create a Directory if it Does Not Exist You can use the Java File class to create directories if they don't already exists. The File class contains the method mkdir() and mkdirs() for that purpose. The mkdir() method creates a single directory if it does not already exist.

Does mkdir check if directory exists?

mkdir WILL give you an error if the directory already exists. mkdir -p WILL NOT give you an error if the directory already exists. Also, the directory will remain untouched i.e. the contents are preserved as they were.


2 Answers

Try the -Force parameter:

New-Item -ItemType Directory -Force -Path C:\Path\That\May\Or\May\Not\Exist 

You can use Test-Path -PathType Container to check first.

See the New-Item MSDN help article for more details.

like image 179
Andy Arismendi Avatar answered Sep 21 '22 09:09

Andy Arismendi


$path = "C:\temp\NewFolder" If(!(test-path $path)) {       New-Item -ItemType Directory -Force -Path $path } 

Test-Path checks to see if the path exists. When it does not, it will create a new directory.

like image 23
Guest Avatar answered Sep 21 '22 09:09

Guest