Skip to content

Instantly share code, notes, and snippets.

@midnightfreddie
Last active April 24, 2018 04:15
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save midnightfreddie/933726eb5b6c881591f979af5937c493 to your computer and use it in GitHub Desktop.
Save midnightfreddie/933726eb5b6c881591f979af5937c493 to your computer and use it in GitHub Desktop.
<#
.Synopsis
Roll dice
.DESCRIPTION
Given a role-playing description of dice, e.g. "2d6", return an object
with the randomly rolled results
.EXAMPLE
Invoke-Dice 2d6
.EXAMPLE
Invoke-Dice 2d6 -Bonus 3
.INPUTS
Dice - A string in the format "2d6" with the number of rolls, "d" and then
the number of sides on each die
.INPUTS
Bonus - A number to add to the total of the natural dice roll. Defaults to 0.
#>
function Invoke-Dice {
[CmdletBinding()]
Param (
[Parameter(Mandatory=$true)]
[string]$Dice,
[int]$Bonus = 0
)
[int]$NumDice, [int]$DieSides = $Dice.Split('d')
$DieRolls= 1..$NumDice | ForEach-Object {
[int](Get-Random -Maximum $DieSides) +1
}
$Sum = ($DieRolls | Measure-Object -Sum).Sum
$Out = New-Object psobject -Property ([ordered]@{
DieRolls = $DieRolls
Sum = $Sum
Bonus = $Bonus
Total = $Sum + $Bonus
})
Write-Output $Out
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment