DarkLite1
DarkLite1

Reputation: 14695

Function to create folders

This works fine to create multiple folders that are piped:

Function Add-Folders {

    $Permissions.Folder | ForEach-Object { 

        if (Test-Path "$Path\$_" -PathType Container) { 
            Write-Verbose "-Exists: $Path\$_"
        } 
        else {
            New-Item "$Path\$_" -Type Directory  > $null
            Write-Verbose "-Created: $Path\$_"
        }
    } 
}

This one doesn't work when I pipe multiple folder names to it:

Function Make-Folders {
    [CmdletBinding(SupportsShouldProcess=$True)]
    Param(
        [parameter(Mandatory=$true,Position=0)]
        [ValidateScript({Test-Path $_ -PathType Container})]
        [ValidateNotNullOrEmpty()]
        [String]$Path,
        [parameter(Mandatory=$true,ValueFromPipeline=$true,Position=1)]
        [ValidateNotNullOrEmpty()]
        [String[]]$Name
    )

    $Name | ForEach-Object { 

        if (Test-Path "$Path\$_" -PathType Container) { 
            Write-Verbose "-Exists: $Path\$_"
        } 
        else {
            New-Item "$Path\$_" -Type Directory  > $null
            Write-Verbose "-Created: $Path\$_"
        }
    } 
}
$Permissions.Folder | Make-Folders -Path c:\Root -Verbose

When I check in debug mode I can see that $Name only receives the last folder name available in Permissions.Folder. I don't really understand why it's not piping everything.. Probably I'm missing something obvious here.

Upvotes: 0

Views: 790

Answers (1)

DarkLite1
DarkLite1

Reputation: 14695

Fixed my stupid mistake, I was missing the Process section:

Function Make-Folders {
    [CmdletBinding(SupportsShouldProcess=$True)]
    Param(
        [parameter(Mandatory=$true,Position=0)]
        [ValidateScript({Test-Path $_ -PathType Container})]
        [ValidateNotNullOrEmpty()]
        [String]$Path,
        [parameter(Mandatory=$true,ValueFromPipeline=$true,Position=1)]
        [ValidateNotNullOrEmpty()]
        [String[]]$Name
    )
    Process {

        $Name | ForEach-Object { 

            if (Test-Path "$Path\$_" -PathType Container) { 
                Write-Verbose "-Exists: $Path\$_"
            } 
            else {
                New-Item "$Path\$_" -Type Directory  > $null
                Write-Verbose "-Created: $Path\$_"
            }
        }
    } 
}


$Permissions.Folder | Make-Folders -Path $Target -Verbose

Sorry guys, my bad.

Upvotes: 1

Related Questions