Create directory if it does not exist Create directory if it does not exist powershell powershell

Create directory if it does not exist


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.


$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.


The following code snippet helps you to create a complete path.

Function GenerateFolder($path) {    $global:foldPath = $null    foreach($foldername in $path.split("\")) {        $global:foldPath += ($foldername+"\")        if (!(Test-Path $global:foldPath)){            New-Item -ItemType Directory -Path $global:foldPath            # Write-Host "$global:foldPath Folder Created Successfully"        }    }}

The above function split the path you passed to the function and will check each folder whether it exists or not. If it does not exist it will create the respective folder until the target/final folder created.

To call the function, use below statement:

GenerateFolder "H:\Desktop\Nithesh\SrcFolder"