How to pass $_ ($PSItem) in a ScriptBlock

后端 未结 3 629
执笔经年
执笔经年 2021-01-06 07:51

I\'m basically building my own parallel foreach pipeline function, using runspaces.

My problem is: I call my function like this:

somePipeline | MyNew         


        
3条回答
  •  囚心锁ツ
    2021-01-06 08:15

    The key is to define $_ as a variable that your script block can see, via a call to Set-Variable.

    Here's a simple example:

    function MyNewForeachFunction {
      [CmdletBinding()]
      param(
        [Parameter(Mandatory)]
        [scriptblock] $ScriptBlock
        ,
        [Parameter(ValueFromPipeline)]
        $InputObject
      )
    
      process {
        $PSInstance = [powershell]::Create()
    
        # Add a call to define $_ based on the current pipeline input object
        $null = $PSInstance.
          AddCommand('Set-Variable').
            AddParameter('Name', '_').
            AddParameter('Value', $InputObject).
          AddScript($ScriptBlock)
    
        $PSInstance.Invoke()
      }
    
    }
    
    # Invoke with sample values.
    1, (Get-Date) | MyNewForeachFunction { "[$_]" }
    

    The above yields something like:

    [1]
    [10/26/2018 00:17:37]
    

提交回复
热议问题