Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- 1..100 | % { switch ( $_ ) { { $_ % 3 -eq 0 } { Write-Host -NoNewline "Fizz" } { $_ % 5 -eq 0 } { Write-Host -NoNewline "Buzz" } default {Write-Host -NoNewline $_ } } Write-Host ""}
- #
- # Break it down
- #
- # the .. create an array between the values asked
- $numbers = 1..100
- foreach($number in $numbers)
- {
- # Powershell's switch is special.
- switch( $number )
- {
- # you can do logic in the case statement and enter the script block if its $true
- { $number % 3 -eq 0 }
- {
- Write-Host -NoNewline "Fizz"
- }
- # if the case doesn't break then it will evaluate each case in turn
- { $number % 5 -eq 0 }
- {
- Write-Host -NoNewline "Buzz"
- }
- # and has default if no matches
- default
- {
- Write-Host -NoNewline $number
- }
- }
- # stick a newline on at the end
- Write-Host ""
- }
- cls
- # If you wanted it as an array instead
- # you can get the ouput of any call (including foreach, switch, etc)
- $list = foreach($number in $numbers)
- {
- # so we collect the result of the switch
- $output = switch( $number )
- {
- { $number % 3 -eq 0 }
- {
- # just put it on the script block's return
- "Fizz"
- }
- { $number % 5 -eq 0 }
- {
- "Buzz"
- }
- default
- {
- $number
- }
- }
- # output at this point with either be a single value or an array of values, so join it together and put that on the return of the foreach script block
- $output -join ""
- }
- Write-Host $list
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement