PowerShell Create Folder if it does not exist

PowerShell Create Folder

[su_heading]Post Last Updated on 21.07.2015[/su_heading]

Sometimes when creating a script it is necessary and useful to have PowerShell create folder if it does not exist this can be easily accomplished with something like the following

# Specify the path
$destDir = "C:ReportPath"

# Check if the folder exist if not create it 

If (!(Test-Path $destDir)) {

   New-Item -Path $destDir -ItemType Directory

}

else {
   
   Write-Host "Directory already exists!"

}

I used the full New-Item syntax on purpose but of course you could use the following form to have PowerShell create the folder

# Check if the folder exist if not create it 

If (!(Test-Path $destDir)) {

   md $dir

}

An alternate form that will actually save you some time is simply using the -force parameters like this

New-Item DirName -ItemType Directory -Force

Result will be exactly the same and PowerShell will create the folder saving you some typing which will not hurt, finally if you’re feeling brave you can even use the .Net method and the above line would read

[system.io.directory]::CreateDirectory("C:ReportPath")

I like the last method the least as I find it difficult to integrate that in a script but it works nonetheless so it’s really up to your preference.

Advertisements

5 thoughts on “PowerShell Create Folder if it does not exist

    1. Thanks Bernard, yes you’re correct as habit I usually log or print some kind of message when dealing with Directory creation hence the habit of having a check in place but as you suggested the -Force saves some typing which is always good.

      I’ll edit the post with your suggestion, thanks again!

      Like

  1. the very top code example is still relevant as of 06/2016. I don’t like the -force switch b/c it suppresses any error handling routines.

    Like

    1. Yes completely agree with you I usually tend to avoid the -force switch but sometimes can have its uses only reason for which I’ve reported it in here.

      Like

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s