How to use a parameterized script block with Where-Object in Powershell?

Is there a better approach for passing information to script blocks in filter scripts where-objectthan with parent type variables?

Background:

I have a script that searches for files with unregistered and / or modified source files against the original control and has a parameter that allows it to perform a more comprehensive search. I use where-objectin several places with the block script object contained in the script -scoped variable, which I configure based on the input parameters in the script.

So, if you ask for a thorough search, the filter will compare the candidate file with all the TFS files to make sure that the file is not in the original management, if you choose a less thorough search, the filter will only compare for files with verified files to check whether the file has been modified but not uploaded.

Individual script blocks relate to script -scoped variables containing the results of executing queries to the source control.

So my problem is that I want to get rid of the global variable (script -level) and pass all the necessary information to the script blocks as parameters for the script blocks. If I used invoke-command, I would use a parameter ArgumentListfor this. where-objectit seems not. One drawback of using variable references with parental restrictions in script blocks is that I cannot change these variables, so I cannot perform lazy initialization (or at least I haven't figured it out yet, without being an expert on rules Review for Powershell.)

+5
source share
3 answers

Just to talk a little about what Kate said, you can do it like this:

ps> $x=2
ps> 1..5 | where (& {param($v); { $_ -eq $v }.getnewclosure() } $x )
2

implict $args, , $args . , , .

$x , (get-x).

, , , scriptblocks. , , , [ ]. .

, . , , , .

-Oisin

+6

GetNewClosure() , , , :

function FilterProcs([scriptblock]$scriptblock)
{
    Get-Process | Where $scriptblock
}

$name = 'Notepad'

& {
    $name = 'PowerShell'
    FilterProcs {$_.Name -eq $name}.GetNewClosure()
}

$name

$name , script . , , , .

, , Foreach-Object:

function FilterProcs([scriptblock]$scriptblock, [object[]]$argumentList)
{
    Get-Process | Foreach {if (&$scriptblock @argumentList){$_}}
}

FilterProcs {param($name, $id) ($_.Name -match $name -and $_.Id -eq $id)} `
            -ArgumentList 'PowerShell_ISE',$pid

P.S. , PowerShellin.: -)

+5

exsiting scriptblock $args, :

$x=2
 1..5 | where (& {[scriptblock]::create('$_ -eq ' + $args) } $x )


 2

, script , getnewclosure . 10000 , script $args 5,3 , getnewclosure 7,9.

+3

All Articles