Advertisement
Guest User

Powershell fizzbuzz

a guest
Feb 22nd, 2017
92
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. 1..100 | % { switch ( $_ ) { { $_ % 3 -eq 0 } { Write-Host -NoNewline "Fizz" } { $_ % 5 -eq 0 } { Write-Host -NoNewline "Buzz" } default {Write-Host -NoNewline $_ } } Write-Host ""}
  2.  
  3.  
  4.  
  5. #
  6. # Break it down
  7. #
  8.  
  9.  
  10. # the .. create an array between the values asked
  11. $numbers = 1..100
  12.  
  13. foreach($number in $numbers)
  14. {
  15.     # Powershell's switch is special.
  16.     switch( $number )
  17.     {
  18.         # you can do logic in the case statement and enter the script block if its $true
  19.         { $number % 3 -eq 0 }
  20.         {
  21.             Write-Host -NoNewline "Fizz"            
  22.         }
  23.  
  24.         # if the case doesn't break then it will evaluate each case in turn
  25.         { $number % 5 -eq 0 }
  26.         {
  27.             Write-Host -NoNewline "Buzz"
  28.         }
  29.        
  30.         # and has default if no matches
  31.         default
  32.         {
  33.             Write-Host -NoNewline $number
  34.         }        
  35.     }
  36.     # stick a newline on at the end
  37.     Write-Host ""
  38. }
  39.  
  40.  
  41.  
  42.  
  43.  
  44.  
  45. cls
  46.  
  47. # If you wanted it as an array instead
  48. # you can get the ouput of any call (including foreach, switch, etc)
  49. $list = foreach($number in $numbers)
  50. {
  51.     # so we collect the result of the switch
  52.     $output = switch( $number )
  53.     {        
  54.         { $number % 3 -eq 0 }
  55.         {
  56.             # just put it on the script block's return
  57.             "Fizz"            
  58.         }
  59.        
  60.         { $number % 5 -eq 0 }
  61.         {
  62.             "Buzz"
  63.         }
  64.        
  65.         default
  66.         {
  67.             $number
  68.         }        
  69.     }
  70.    
  71.     # 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
  72.     $output -join ""
  73. }
  74.  
  75. Write-Host $list
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement