PowerShell if / else Test-Path

For some reason, the if / else clause does not work. It creates directories, but does not execute the if part, saying "The folder already exists." It must be something super obvious, I don’t see it 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 
    }
} 

Example contents of a CSV file:

Name
Folder1
Folder2
Folder3
Folder3\Folder1

The solution thanks to the help of 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)"
    }
} 
+4
source share
1 answer

We need a csv sample to help you. The most likely problem is that the given path is equal to the string object ( $folder). CSV has headers, so you need to access the property using a path. Example.

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

UPDATE: The example was updated with the correct property name after providing the csv sample.

+3
source

Source: https://habr.com/ru/post/1538551/


All Articles