Jump to content

Programming Fundamentals/Arrays/PowerShell

From Wikiversity

arrays.ps1

[edit | edit source]
# This program demonstrates array processing, including:
# display, total, max, min, parallel arrays, sort
# multidimensional arrays, and dynamic arrays.
#
# References:
#     https://en.wikiversity.org/wiki/PowerShell/Arrays_and_Hash_Tables

function Display-Array($array)
{
    for ($index = 0; $index -lt $array.Length; $index++)
    {
        Write-Host $array[$index]
    }
}

function Sum-Array($array)
{
    $total = 0
    for ($index = 0; $index -lt $array.Length; $index++)
    {
        $total += $array[$index]
    }
    return $total
}

function Max-Array($array)
{
    $maximum = $array[0]
    for ($index = 1; $index -lt $array.Length; $index++)
    {
        if ($maximum -lt $array[$index])
        {
            $maximum = $array[$index]
        }
    }
    return $maximum
}

function Min-Array($array)
{
    $minimum = $array[0]
    for ($index = 1; $index -lt $array.Length; $index++)
    {
        if ($minimum -gt $array[$index])
        {
            $minimum = $array[$index]
        }
    }
    return $minimum
}

function Display-Parallel($names, $ages)
{
    for ($index = 0; $index -lt $names.Length; $index++)
    {
        Write-Host $($names[$index] + ' is ' + 
            $ages[$index].ToString() + ' years old')
    }
}

function Display-Multidimensional()
{
    $game = @('X', 'O', 'X'), 
        @('O', 'O', 'O'), 
        @('X', 'O', 'X')

    for($row = 0; $row -lt 3; $row++)
    {
        for($column = 0; $column -lt 3; $column++)
        {
            Write-Host -NoNewline $game[$row][$column]
            if ($column -lt 2)
            {
                Write-Host -NoNewline " | "
            }
        }
        Write-Host
    }
}    

function Dynamic-Array()
{
    $array = @()
    for($index = 0; $index -lt 5; $index++)
    {
        $array += Get-Random -Maximum 100
    }
    Display-Array $array
}

function Main()
{
    $names = @('Lisa', 'Michael', 'Ashley', 'Jacob', 'Emily')
    $ages = @(49, 48, 26, 19, 16)

    Display-Array $names
    Display-Array $ages

    $total = Sum-Array $ages
    $maximum = Max-Array $ages
    $minimum = Min-Array $ages

    Write-Host "Total: $total"
    Write-Host "Maximum: $maximum"
    Write-Host "Minimum: $minimum"

    Display-Parallel $names $ages

    $ages = $ages | Sort-Object
    Display-Array $ages

    Display-Multidimensional
    Dynamic-Array
}

Main

Try It

[edit | edit source]

Copy and paste the code above into one of the following free online development environments or use your own PowerShell compiler / interpreter / IDE.

Online

[edit | edit source]
  • There are some options, but none are fully functional at this time.

Windows

[edit | edit source]

macOS / Linux

[edit | edit source]

See Also

[edit | edit source]