PSDice.psm1

function Invoke-DiceRoll {
    <#
    .SYNOPSIS
        Rolls one or more dice and returns the results.
    .DESCRIPTION
        Rolls the specified number of dice, each with the specified number of sides.
        Each die is rolled independently. Optionally returns the sum of all rolls.
    .PARAMETER Sides
        Number of faces on each die. Must be 2 or greater. Defaults to 6.
    .PARAMETER Count
        How many dice to roll. Must be 1 or greater. Defaults to 1.
    .PARAMETER Sum
        When specified, returns a single integer representing the sum of all rolls.
        When omitted, returns an array of individual roll results.
    .EXAMPLE
        Invoke-DiceRoll
        Rolls a single six-sided die and returns a number between 1 and 6.
    .EXAMPLE
        Invoke-DiceRoll -Count 3
        Rolls three six-sided dice and returns an array of three integers, each between 1 and 6.
    .EXAMPLE
        Invoke-DiceRoll -Count 3 -Sum
        Rolls three six-sided dice and returns their sum as a single integer between 3 and 18.
    .EXAMPLE
        Invoke-DiceRoll -Sides 20
        Rolls a single twenty-sided die and returns a number between 1 and 20.
    .NOTES
        Compatible with Windows PowerShell 5.1 and PowerShell 7+.
    .LINK
        https://github.com/Ba4bes/PowerPilot
    #>

    [OutputType([int[]])]
    [CmdletBinding()]
    param(
        [Parameter()]
        [ValidateRange(2, [int]::MaxValue)]
        [int]$Sides = 6,

        [Parameter()]
        [ValidateRange(1, [int]::MaxValue)]
        [int]$Count = 1,

        [Parameter()]
        [switch]$Sum
    )

    $StartVariables = (Get-Variable).Name
    Write-Verbose "Starting Function Invoke-DiceRoll (Sides=$Sides, Count=$Count, Sum=$Sum)"

    $Results = for ($i = 1; $i -le $Count; $i++) {
        $Roll = Get-Random -Minimum 1 -Maximum ($Sides + 1)
        Write-Verbose "Die $i rolled: $Roll"
        $Roll
    }

    if ($Sum) {
        $Total = ($Results | Measure-Object -Sum).Sum
        Write-Verbose "Sum of rolls: $Total"
        [int]$Total
    }
    else {
        [int[]]$Results
    }

    $NewVariables = Get-Variable | Where-Object { $StartVariables -notcontains $_.Name }
    Clear-Variable $NewVariables.Name -ErrorAction SilentlyContinue
    Write-Verbose "Function Invoke-DiceRoll done"
}