1

I have two functions one which outputs a set of directories And one needs to receive that set and do a foreach on it, however it seems the second function is only receiving one of the directories (the last one).

What am I doing wrong.

Get-Directories {
    return Get-ChildItem | Where-Object { $_.PSIsContainer -eq $True }
}
function Invoke-Build {
    [CmdletBinding()]
    Param(
    [Parameter(Mandatory=$True,ValueFromPipeline=$True,ValueFromPipelineByPropertyName=$True)]
    [string[]]$directories
)
Write-Output $dir
foreach ($dir in $directories) {
    Set-Location $dir
    Build
    Set-Location ..
}

Get-Directories | Invoke-Build

The output though is just the last directory found by Get-Directories. I need the second function to accept array input as I plan to make it do things asynchronously.

1
  • 2
    Use process{...} block. Commented Jan 22, 2016 at 9:05

2 Answers 2

1

You need to include a PROCESS block in your Invoke-Build function.

function Invoke-Build 
{
  [CmdletBinding()]
  Param
  (
    [Parameter(Mandatory = $True,
               ValueFromPipeline = $True,
               ValueFromPipelineByPropertyName = $True)]
    [string[]]$directories
  )

  PROCESS 
  {
    Write-Output $directories
  }
}

If you call the function like this:

"dir1", "dir2", "dir3" | Invoke-Build

The function will iterate over the directories one at a time.

More Information on implementing pipeline support can be found here: http://learn-powershell.net/2013/05/07/tips-on-implementing-pipeline-support/

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

Comments

0

PetSerAl's comment was spot on.

I changed the second function as follows

function Invoke-Build {
    [CmdletBinding()]
    Param(
        [Parameter(Mandatory=$True,ValueFromPipeline=$True,ValueFromPipelineByPropertyName=$True)]
        [string[]]$directories
    )
    Begin { Write-Output "Starting" }
    Process {
        Set-Location $_
        build
        Set-Location ..
    }
    End { Write-Output "Done" }

1 Comment

you can also use the foreach inside the process block to specify an array of values ( when not using the pipeline)

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.