4

For some reason the if/else clause is not working. It does create the directories but it doesn't execute the if part by saying 'Folder exists already'. It must be something super obvious I am not seeing as a noob. Thank you for your help.

Set-Location "\\domain.net\Target" 

$Folders = Import-Csv "C:\Temp\Test.csv" 

ForEach ($Folder in $Folders) { 

    if (Test-Path -LiteralPath $Folder -PathType Container)
    { 
    Write-Host "Folder exists already"
    } 
    else 
    {
    New-Item $Folder.Name -Type Directory 
    }
} 

CSV-file content example:

Name
Folder1
Folder2
Folder3
Folder3\Folder1

Solution thanks to the help from the guys below:

#================= VARIABLES ==================================================
 $Target = "\\Temp\Target" 
 $InputF = "\\Temp\Downloads\Test.csv" 
#
# CSV-File format:
# Name
# Dir1
# Dir2
# Dir3\Subdir1

CLS
Write-Host "Folder creation`n"

#$Target = Read-Host "Provide the full UNC-Path where we need to create subfolders"
#$InputF = Read-Host "Provide the full UNC-Path & name of the CSV input file"

$Folders = Import-Csv $InputF 
Set-Location $Target

Write-Host "`nStarting folder creation:`n"

ForEach ($Folder in $Folders) { 

    if (Test-Path -LiteralPath $Folder.Name -PathType Container)
    { 
    Write-Host "-Exists: $Target\$($Folder.Name)" -ForegroundColor DarkGray
    } 
    else 
    {
    New-Item $Folder.Name -Type Directory  > $null
    Write-Host "-Created: $Target\$($Folder.Name)"
    }
} 

1 Answer 1

3

We need a sample of the csv to help you. The most likely problem is that set path equal to the row-object($folder). A CSV has headers, so you need to access the property with the path.. Ex.

if (Test-Path -LiteralPath $Folder.Name -PathType Container)

UPDATE: Example updated with correct property name after the csv sample was provided.

Sign up to request clarification or add additional context in comments.

3 Comments

CSV-File content added to initial post
use $Folder.Name in the if clause, as in if (Test-Path -LiteralPath $Folder.Name -PathType Container) to access the folder name
Yes, you are right. Changing the if clause to $Folder.Name fixed it. Thank you very much! :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.