Skip to content

Instantly share code, notes, and snippets.

@JustinGrote
Last active July 22, 2022 01:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save JustinGrote/725471be625e4119705cce7e9c32eea6 to your computer and use it in GitHub Desktop.
Save JustinGrote/725471be625e4119705cce7e9c32eea6 to your computer and use it in GitHub Desktop.
Example of Filter to convert a ForEach
#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
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