0

I want to write a cmdlet that invokes a call back method. When invoking the callback method, I want to be able to use the automatic variable $_. This is so that I don't have to

For example, let's say my function is an implementation similar to ForEach-Object:

(Note - I know I could use ForEach-Object to this exact same thing. I'm just presenting this as a simplified example for something else that i need to do)

function Invoke-MyCustomPsCmdlet {
    [CmdletBinding()]
    param(
        [Parameter(Mandatory=$true,ValueFromPipeline=$true)]
        [int[]] $input,

        [scriptblock] $callback
    )

    # Do somethign meaningful here.
    Write-Output "Cmdlet: $input"

    foreach($i in $input){
        # How to invoke the $callback so that $i will be passed on to the $_ of the callback scriptblock?
        #$i | $callback
    }

}

This is how i want to invoke it (with $_)

1,2,3,4,5 | Invoke-MyCustomPsCmdlet -callback { Write-Output "Callback: $_" }

And my expectation is to have this output

Cmdlet: 1 2 3 4 5
Callback: 1
Callback: 2
Callback: 3
Callback: 4
Callback: 5
Nandun
  • 1,802
  • 2
  • 20
  • 35
  • 1
    Just use `ForEach-Object`: `$input |ForEach-Object $callback` :) – Mathias R. Jessen May 29 '20 at 23:44
  • I'm just trying to find out how $_ is used in a cmdlet i'm implementing that is very similar to ForEach-Object – Nandun May 30 '20 at 00:04
  • 5
    the variable `$Input` is a _reserved automatic variable_. you should NEVER set it or write to it unless you are totally certain you need to do so. try using something that is not an automatic variable ... [*grin*] – Lee_Dailey May 30 '20 at 01:39

0 Answers0