Powershell To Create Folder If Not Exists

25,127

Solution 1

if (!(Test-Path $FolderToCreate -PathType Container)) {
    New-Item -ItemType Directory -Force -Path $FolderToCreate
}

Solution 2

Try using the -Force flag - it checks for every single subdirectory when they don't exist, it would simply create it and go for the next one and never throw an error.

In the example below, you need 7 nested sub-directories, with one single line you can create anyone that doesn't exist.

You can also re-run it as many as times as you like, and it is designed to never throw an error!

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

Solution 3

other solution :

if (![System.IO.Directory]::Exists($FolderToCreate ))
{
     New-Item -ItemType Directory -Force -Path $FolderToCreate
}
Share:
25,127
BellHopByDayAmetuerCoderByNigh
Author by

BellHopByDayAmetuerCoderByNigh

Updated on December 28, 2021

Comments

  • BellHopByDayAmetuerCoderByNigh
    BellHopByDayAmetuerCoderByNigh over 2 years

    I am attempting to parse a file name in a folder and store parts of the filename in variables. Check! I then want to take one of the variables and check if that folder name exists in a different location, and if it does not create it. If I use Write-Host the folder name is a valid path, and the folder name does not exist, but upon execution of the script the folder still is not created.

    What should I do to create the folder if it does not exist?

    $fileDirectory = "C:\Test\"
    $ParentDir = "C:\Completed\"
    foreach ($file in Get-ChildItem $fileDirectory){
    
        $parts =$file.Name -split '\.'
    
        $ManagerName = $parts[0].Trim()
        $TwoDigitMonth = $parts[1].substring(0,3)
        $TwoDigitYear = $parts[1].substring(3,3)
    
        $FolderToCreate = Join-Path -Path $ParentDir -ChildPath $ManagerName
    
        If(!(Test-Path -path "$FolderToCreate\"))
        {
            #if it does not create it
            New-Item -ItemType -type Directory -Force -Path $FolderToCreate
        }
    
    }
    
  • Toby Speight
    Toby Speight almost 7 years
    Whilst this code snippet is welcome, and may provide some help, it would be greatly improved if it included an explanation of how it addresses the question. Without that, your answer has much less educational value - remember that you are answering the question for readers in the future, not just the person asking now! Please edit your answer to add explanation, and give an indication of what limitations and assumptions apply.
  • GermanC
    GermanC about 6 years
    Upvoting for pointing the need of Force for the creation of the whole tree.
  • Andreas
    Andreas over 4 years
    Caveat: The folder may be created by another process in between Test-Path and New-Item.
  • Matthew MacFarland
    Matthew MacFarland about 3 years
    I recommend if (-not(Test-Path... for better readability. The ! can be hard to spot.