Last active
August 29, 2015 14:24
-
-
Save mprahl/859c3d5419a37e9c411c to your computer and use it in GitHub Desktop.
This Is An Advanced FizzBuzz Function Using PowerShell
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
# This is a function that receives a numerical range and for multiples of three prints “Fizz” instead of the number and for | |
# the multiples of five prints “Buzz”. For numbers which are multiples of both three and five, the function prints “FizzBuzz” | |
function FizzBuzz { | |
# Allow the use of standard PowerShell cmdlet features, in this instance the function is using Write-Verbose | |
[CmdletBinding()] | |
Param ( | |
# Specify that the $min variable is mandatory and must be an integer | |
[parameter(Mandatory=$true, ValueFromPipeline=$false)] | |
[int]$min, | |
# Specify that the $max variable is mandatory and must be an integer | |
[parameter(Mandatory=$true, ValueFromPipeline=$false)] | |
[int]$max | |
) | |
Process { | |
# A loop to go through the range specified | |
for ($i = $min; $i -lt $max; $i++) { | |
# If the current iteration ($i) is divisible by 3 and 5, print FizzBuzz | |
if ( (($i % 3) -eq 0) -and (($i % 5) -eq 0)) { | |
# Write to the screen if the -Verbose parameter is suppled | |
Write-Verbose "$i is a multiple of 3 and 5" | |
# Write out FizzBuzz to the screen | |
Write-Host -NoNewline "FizzBuzz" | |
} | |
# If the current iteration ($i) is divisible by 3, print Fizz | |
elseif (($i % 3) -eq 0) { | |
# Write to the screen if the -Verbose parameter is suppled | |
Write-Verbose "$i is a multiple of 3" | |
# Write out Fizz to the screen | |
Write-Host -NoNewline "Fizz" | |
} | |
# If the current iteration ($i) is divisible by 5, print Buzz | |
elseif (($i % 5) -eq 0) { | |
# Write to the screen if the -Verbose parameter is suppled | |
Write-Verbose "$i is a multiple of 5" | |
# Write out Buzz to the screen | |
Write-Host -NoNewline "Buzz" | |
} | |
# If the iteration isn't divisible by 3 or 5, then simply print it to the screen | |
else { | |
# Write to the screen if the -Verbose parameter is suppled | |
Write-Verbose "$i is not a multiple of 3 or 5" | |
# Write out the iteration to the screen | |
Write-Host -NoNewline $i | |
} | |
# If it isn't the last iteration, print a comma and space to the screen | |
if ($i -ne ($max -1)) { | |
Write-Host -NoNewline ", " | |
} | |
} | |
} | |
} | |
# Call the function with a range of 1 to 100 | |
FizzBuzz 1 100 | |
# If you want the verbose features, call the function as follows (without the hashtag) | |
#FizzBuzz 1 100 -Verbose |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment