[astuce] 'Where' à la 'LINQ' avec PowerShell 2.0
'Where' à la 'LINQ' avec PowerShell 2.0
Salut,
cette petite astuce est une amélioration de la nouvelle syntaxe declarative 'Where' en PS 4.0
Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
|
<?xml version="1.0" encoding="utf-8" ?>
<Types>
<Type>
<Name>System.Array</Name>
<Members>
<ScriptMethod>
<Name>Where</Name>
<Script>
$arg = $args[0] -as [String]
$members = ($this |gm -Type *property |select -Unique -Expand name) +'PSItem'
$members | foreach {
if($arg -match $_) {
if($Matches[0] -eq 'PSItem')
{ $arg=$arg.replace($($Matches[0]),'$_')
}
else
{ $arg=$arg.replace($($Matches[0]),$('$_.' + $Matches[0]))
}
}
}
$sb=$ExecutionContext.InvokeCommand.NewScriptBlock($arg)
$this | Where-Object -Filter $sb
</Script>
</ScriptMethod>
</Members>
</Type>
</Types> |
après avoir updater votre fichier de configuration vous pouvez l'utiliser ainsi:
Code:
1 2 3
| PS II> (1..10).Where('PSitem -gt 5 -and (PSitem -band 1)')
7
9 |
Code:
1 2 3 4 5 6 7 8 9 10
| PS II> $dir = Get-ChildItem c:\Temp
PS II> $dir.Where('!psiscontainer -and length -gt 10mb')
Répertoire*: c:\Temp
Mode LastWriteTime Length Name
---- ------------- ------ ----
-a--- 10/02/2012 13:30 12mb f35.exe |
Code:
1 2 3 4 5 6 7 8 9 10
| PS > $dir.Where('$true')
Répertoire*: c:\Temp
Mode LastWriteTime Length Name
---- ------------- ------ ----
d---- 01/05/2012 18:22 Scripts
-a--- 10/02/2012 13:30 12mb f35.exe |
Code:
1 2 3
| PS II> (get-process).Where('path -like "*Scripts*"').Where('StartTime')
PS II> # ou bien:
PS II> (get-process).Where('path -like "*Scripts*" -and StartTime') |