Programming Fundamentals/Strings/PowerShell

From Wikiversity
Jump to navigation Jump to search

strings.ps1[edit]

# This program splits a given comma-separated name into first and last name
# components and then displays the name.
#
# References:
#     https://en.wikiversity.org/wiki/PowerShell

function Get-Name()
{
    Do {
        Write-Host 'Enter name (last, first):'
        $name = Read-Host
        $index = $name.IndexOf(',')
    } While ($index -lt 0);
    return $name.Trim()
}

function Get-Last($name)
{
    $index = $name.IndexOf(',')
    if ($index -lt 0)
    {
        $last = ''
    }
    else 
    {
        $last = $name.Substring(0, $index).Trim()
    }

    return $last
}

function Get-First($name)
{
    $index = $name.IndexOf(',')
    if ($index -lt 0)
    {
        $first = ''
    }
    else 
    {
        $first = $name.Substring($index + 1).Trim()    
    }

    return $first
}

function Display-Name($first, $last)
{
    Write-Host "Hello $first $last!"
}

function Main()
{
    $name = Get-Name
    $last = Get-Last $name
    $first = Get-First $name
    Display-Name $first $last
}

Main

Try It[edit]

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]

  • There are some options, but none are fully functional at this time.

Windows[edit]

macOS / Linux[edit]

See Also[edit]