Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
    }

}
like image 389
BellHopByDayAmetuerCoderByNigh Avatar asked Feb 10 '17 14:02

BellHopByDayAmetuerCoderByNigh


People also ask

How do you create a folder if it doesn't exist PowerShell?

PowerShell Create Directory If Not Exists using Test-Path If a directory exists then it will return $True. If a path or directory is missing or doesn't exist, it will return $False. Using PowerShell New-Item cmdlet, it will create directory if not exists using Test-Path.

How do I create a folder in PowerShell script?

To create a folder in PowerShell, use the New-Item cmdlet indicating the location and name of the folder and set the itemType parameter with the value Directory to indicate that you want to create a folder.

How do you check if a directory exists or not in PowerShell?

The Test-Path Cmdlet$Folder = 'C:\Windows' "Test to see if folder [$Folder] exists" if (Test-Path -Path $Folder) { "Path exists!" } else { "Path doesn't exist." } This is similar to the -d $filepath operator for IF statements in Bash. True is returned if $filepath exists, otherwise False is returned.


1 Answers

if (!(Test-Path $FolderToCreate -PathType Container)) {
    New-Item -ItemType Directory -Force -Path $FolderToCreate
}
like image 90
David Brabant Avatar answered Sep 22 '22 23:09

David Brabant