none
Advanced function runs Begin block before pipeline input is executed - can I change this behavior? RRS feed

  • Question

  • Hi,

    I have an advanced function that accepts pipeline input. In my begin block I'm doing a bunch of setup stuff such as start-transcript.

    At the command prompt I'm running this:  get-aduser bogususername | my-function ...

    This runs through by begin block (starting the transcript, etc) and then finally errors on the get-aduser (because of the bogus username) when it gets to the process block and terminates, thus leaving my start-transcript running.

    Is there a way to change this behavior so the input side of the pipe completes (and errors) before my script runs the begin block?

    I'm currently running Powershell v4

    Thanks.
    Buzzy

    • Moved by Bill_Stewart Tuesday, November 7, 2017 10:58 PM Unanswerable drive-by question
    Friday, October 6, 2017 10:13 PM

All replies

  • You cannot change the behavior of the "Begin" pipeline processing.


    \_(ツ)_/

    Friday, October 6, 2017 11:10 PM
  • Instead of that you should try to add the Get-aduser -user $user to add it to your function in your begin statement. Then add $user in your functions parameter sets.

    Then you can pass the $user as parameter to your function and it will run that command first.

    Saturday, October 7, 2017 2:52 AM
  • Instead of that you should try to add the Get-aduser -user $user to add it to your function in your begin statement. Then add $user in your functions parameter sets.

    Then you can pass the $user as parameter to your function and it will run that command first.

    Why would anyone think this is a good idea?

    Spend some time reading some of te many food blogs and books the explain how PowerShell and the pipeline work.  Stop guessing and trying to hack everything.  Programming is a discipline that takes learning.  It is not a toy that can be imagined to be anything you want.

    There I NO way to run a pipeline that does not call all begin blocks of all CmdLets in the pipeline before it processes any object.

    Passing a parameter requires that the begin block is executed.  It cannot prevent the block from running.  If you need custom behavior then process the function in side a "ForEach-Object".

    <commad>|<command>|ForEach-Object{ <you function and parameters> } | ... more CmdLets


    \_(ツ)_/

    Saturday, October 7, 2017 3:48 AM