Thursday, August 18, 2016

PowerShell - Syntax

Display output in the console:

Write-Host "Hello World"

Variable substitution:

$myvar = " World"
# Displays 'Hello World'
Write-Host "Hello$myvar"

<#
This is how I would
make a block comment
of several lines
#>

Write-Host "Goodbye$myvar"





If/Then/Else:

# This has some problems when the user enters an age less than 10.
# For the sake of learning, enter an age of 10 or higher when prompted.

# Your browser may not show it, but there is a space between $age and -lt

$age = Read-Host "How old are you?"

if ($age -lt 13)
{
    Write-Host "Child"
}
elseif ($age -lt 18)
{
    Write-Host "Teen"
}
else 
{
    Write-Host "Adult"
}



Switch (case):

# This has some problems when the user enters an age less than 10.
# For the sake of learning, enter an age of 10 or higher when prompted.

$age = Read-Host "How old are you?"

switch ($age)
{

    {$_ -lt 13 }
    {
        Write-Host "Child"
    }

    {($_ -lt 18) -and ($_ -gt 12) }
    {
        Write-Host "Teen"
    }

    default
    {
        Write-Host "Adult"
    }

}




Arrays:

# Empty array:
$myArray = @()

# Populated array:
$myArray = "baby", "toddler", "child", "teen", "adult"
$collectionOfAges = 0, 4, 13, 18

#Another way to define arrays:
$myArray = @("baby", "toddler", "child", "teen", "adult")

# Interact with arrays:
# child:
$myArray[2]

#
# This will not work because $myArray is a fixed array
# $myArray.Add("senior")

# So instead we need a dynamic-sized array.
# Here is how to define one:

$myArray = New-Object System.Collections.ArrayList
$myArray.Add("baby")
$myArray.Add("toddler")
$myArray.Add("child")
$myArray.Add("teen")
$myArray.Add("adult")
$myArray.Add("senior")

# senior:
$myArray[5]

Write-Host "non-adults:"
$myArray[0..2]



Hashes:

$myHash = @{
"ford" = "mustang"
"pontiac"  = "solstice"
"chevrolet" = "camaro"
}

# Displays 'mustang'
$myHash["ford"]

# Also displays 'mustang'
$myHash.ford


# Displays 3
$myHash.Count

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.