Is it possible to terminate or stop a PowerShell pipeline from within a filter

后端 未结 8 2188
無奈伤痛
無奈伤痛 2020-12-06 06:27

I have written a simple PowerShell filter that pushes the current object down the pipeline if its date is between the specified begin and end date. The objects coming down

8条回答
  •  无人及你
    2020-12-06 06:47

    Try these filters, they'll force the pipeline to stop after the first object -or the first n elements- and store it -them- in a variable; you need to pass the name of the variable, if you don't the object(s) are pushed out but cannot be assigned to a variable.

    filter FirstObject ([string]$vName = '') {
     if ($vName) {sv $vName $_ -s 1} else {$_}
     break
    }
    
    filter FirstElements ([int]$max = 2, [string]$vName = '') {
     if ($max -le 0) {break} else {$_arr += ,$_}
     if (!--$max) {
      if ($vName) {sv $vName $_arr -s 1} else {$_arr}
      break
     }
    }
    
    # can't assign to a variable directly
    $myLog = get-eventLog security | ... | firstObject
    
    # pass the the varName
    get-eventLog security | ... | firstObject myLog
    $myLog
    
    # can't assign to a variable directly
    $myLogs = get-eventLog security | ... | firstElements 3
    
    # pass the number of elements and the varName
    get-eventLog security | ... | firstElements 3 myLogs
    $myLogs
    
    ####################################
    
    get-eventLog security | % {
     if ($_.timegenerated -lt (date 11.09.08) -and`
      $_.timegenerated -gt (date 11.01.08)) {$log1 = $_; break}
    }
    
    #
    $log1
    

提交回复
热议问题