powershellcreate-directory

Powershell To Create Folder If Not Exists


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
    }

}

Solution

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