Last active
July 22, 2022 01:30
-
-
Save JustinGrote/725471be625e4119705cce7e9c32eea6 to your computer and use it in GitHub Desktop.
Example of Filter to convert a ForEach
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#Filter is just a function with the process{} | |
#block as the default rather than end{}. That's it, it's not scary. | |
# $y = 1..3 | |
# foreach ($x in $y) { | |
# "This is item $x" | |
# } | |
# #Result: | |
# #This is item 1 | |
# #This is item 2 | |
# #This is item 3 | |
# #Easily convert it to this: | |
# filter 🍔 { | |
# "This is item $input" | |
# } | |
filter GetJokes { | |
$PSItem.Results.Joke | |
} | |
filter AddFavoriteJokePrefix { | |
[CmdletBinding(SupportsShouldProcess)] | |
param( | |
[Parameter(Mandatory, ValueFromPipeline)][String]$Joke, | |
#Person who's favorite joke it is. | |
$Person = 'Steven' | |
) | |
if (-not $PSCmdlet.ShouldProcess($Joke, "Make it $Person's favorite")) { return } | |
"$Person's favorite Joke is: $Joke" | |
} | |
function Get-DadJokes ($Person) { | |
Invoke-RestMethod 'https://icanhazdadjoke.com/search' -Headers @{Accept = 'application/json' } | |
| GetJokes | |
| AddFavoriteJokePrefix | |
} | |
Export-ModuleMember Get-DadJokes |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Describe 'FilterExample' { | |
It 'Adds Stevens name' { | |
Import-Module $PSScriptRoot/FilterExample.psm1 -Force | |
Get-DadJokes | |
| Select-Object -First 1 | |
| Should -Match 'Steven' | |
} | |
} | |
Describe 'GetJokes' { | |
BeforeAll { | |
Import-Module $PSScriptRoot/FilterExample.psm1 -Force | |
} | |
It 'FilterExample' { | |
InModuleScope 'FilterExample' { | |
[PSCustomObject]@{ | |
Results = @{ | |
Joke = 'Pester' | |
} | |
} | |
| GetJokes | |
| Should -Be 'Pester' | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment