how to use "if" statements inside pipeline how to use "if" statements inside pipeline powershell powershell

how to use "if" statements inside pipeline


When using where-object, the condition doesn't have to strictly be related to the objects that are passing through the pipeline. So consider a case where sometimes we wanted to filter for odd objects, but only if some other condition was met:

$filter = $true1..10 | ? { (-not $filter) -or ($_ % 2) }$filter = $false1..10 | ? { (-not $filter) -or ($_ % 2) }

Is this kind of what you are looking for?


Have you tried creating your own filter. (A silly) example:

filter MyFilter {   if ( ($_ % 2) -eq 0) { Write-Host $_ }   else { Write-Host ($_ * $_) }}PS> 1,2,3,4,5,6,7,8,9 | MyFilter129425649881


I don't know if my answer can help you but I try :)

1..10 | % {if ($_ % 2 -eq 0) {$_}} 

as you can see I use a loop and for each number between 1 and 10 I check if is even and I display it only in this case.