Programming Fundamentals/Strings/PowerShell

From Wikiversity
Jump to navigation Jump to search

strings.ps1[edit | edit source]

# 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 | 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]