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
}
}
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.
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.
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.
if (!(Test-Path $FolderToCreate -PathType Container)) {
New-Item -ItemType Directory -Force -Path $FolderToCreate
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With