Demo-Variable.ps1


<#PSScriptInfo
 
.VERSION 1.0.1
 
.GUID 06faab35-4c21-4982-97eb-67621775b9ed
 
.AUTHOR Frits van Drie (3-Link.nl)
 
.COMPANYNAME 3-Link Opleidingen
 
.COPYRIGHT free to use and distribute without modifications
 
.TAGS
 
.LICENSEURI
 
.PROJECTURI
 
.ICONURI
 
.EXTERNALMODULEDEPENDENCIES
 
.REQUIREDSCRIPTS
 
.EXTERNALSCRIPTDEPENDENCIES
 
.RELEASENOTES
 
.PRIVATEDATA
 
#>


<#
 
.DESCRIPTION
 Developed by 3-Link Opleidingen for training purposes only
 
#>
 
Param()



# Filename: Demo-Variable.ps1
# Date: 2022-04-13
# Author: Frits van Drie (3-Link)


Get-Command -Noun "Variable"

New-Variable    -Name DemoVar
Remove-Variable -Name DemoVar -ErrorAction SilentlyContinue
Set-Variable    -Name DemoVar -Value "demo"
Get-Variable    -Name DemoVar
Get-Variable DemoVar
Get-Variable DemoVar -ValueOnly
$DemoVar

# User-created variables:
# Automatic variables : Help about_Automatic_Variables -ShowWindow
# Preference variables : Help about_Preference_Variables -ShowWindow

#region: Data types


    ("abc"   ).GetType()      # String
    ('abc'   ).GetType()      # String
    (123     ).GetType()      # Int32
    ("123"   ).GetType()      # String
    (123.6   ).GetType()      # Double
    (Get-Date).GetType()      # DateTime
    ($true   ).GetType()      # Boolean
    @(1,2,3  ).GetType()      # Array

    ( [string]123 ).GetType()

    ('FD00:0:0:5::CAFE').GetType()
    [ipaddress]$b = 'FD00:0:0:5::CAFE'  # type accelerator
    [ipaddress]$c = 'FE80::0:0:5:CAFE'  # type accelerator

    $b.GetType()
    $b | gm
    $b.IsIPv6LinkLocal
    $c.IsIPv6LinkLocal


    ([psobject].Assembly.GetType("System.Management.Automation.TypeAccelerators"))::Get | 
        Select -ExpandProperty keys| Sort | ogv

    # PowerShell uses the [System.Math] library, which consists of many mathematical functions and methods
    [System.Math] | Get-Member -Static -MemberType All

    # Int16 : 2^15 = (-32,768 <=> +32,767)
        [math]::pow(2,15)
    # Int/Int32 : 2^31 = (-2,147,483,648 <=> +2,147,483,647)
        [math]::pow(2,31)
    # Int64 : 2^63 = (-9,223,372,036,854,775,808 <=> +9,223,372,036,854,775,807)
        [math]::pow(2,63)



#endregion: Data types

#region: String and Integer
    $DemoVar = "abc"
    $DemoVar |gm
    $demovar.GetType().Name

    Remove-Variable svc -ea SilentlyContinue
    $Svc = Get-Service sp*
    $Svc | Get-Member
    $Svc.DisplayName
    $svc.GetType()

    Remove-Variable s
    $s = "Spooler"
    $s | Get-Member
    $s.GetType()

    Remove-Variable i
    $i = 25
    $i | Get-Member
    $i.GetType()
    $i = $i+12
    $i.GetType()
    $i

    $i = "25"
    $i.GetType()
    $i = $i+12
    $i.GetType()
    $i
    $i = $i-2500
    $i
    $i.GetType()

    $i = 25
    $i.GetType()
    $i = $i+"12"
    $i.GetType()
    $i
    $i = $i-2500
    $i
    $i.GetType()



    $i = "25"
    $i.GetType()
    Remove-Variable n -ErrorAction SilentlyContinue
    $n = $i
    $n.GetType()

    Remove-Variable m
    $m = $i -as [int32]
    [int32]$m = $i
    $m.GetType()
    $m

    Remove-Variable s
    $s = 25
    $s.GetType()
    $s

    Remove-Variable t
    $s = $s*4
    $t = $s -as [string]
    $t*4
    "="*100
    $t.GetType()
    $t - 5
    $t.GetType()
    $t

    # !!!! Method used to evaluate statements is determined by leftmost object !!!!
    Remove-Variable a
    Remove-Variable b
    $a = "file"
    $b = 3
    ($a*$b) -eq ($b*$a) # Cannot convert value "file" to type "System.Int32"
    ($a*$b)             # filefilefile
    ($b*$a)             # Cannot convert value "file" to type "System.Int32"
    "file" * 3          # leftmost is string: filefilefile
    3 * "file"          # leftmost is int32: Cannot convert value "file" to type "System.Int32"


    Remove-Variable u
    $u = "abc"
    $u.GetType()
    $u -5
    $u.GetType()

    Remove-Variable s
    $s = '25'
    $s = $s/3
    $s
    $s.GetType()
    [string]$s = 25  # strongtyping
    $s+5
    $s = $s/3
    $s
    $s.GetType()

    $s = '25' 
    $s+5
    [string]$s = $s/3 # strongtyping
    $s
    $s.GetType()


    # ==========================================
    $txt = "Demo"
    "Tekst is $txt"
    'Tekst is $txt'
    'Tekst van $txt is $txt'
    # 'Tekst van $txt is' $txt
    'Tekst van $txt is '+ $txt

    Write-Host 'Tekst van $txt is' $txt -BackgroundColor Yellow -ForegroundColor Red
    "Tekst van `$txt is $txt"  # Backtick `

    $svc = Get-Service Spooler
    $svcName = $svc.name
    "Servicename is $svcName"
    "Servicename is $svc.Name"
    "Servicename is $($svc.Name)"
    "Servicename is " + $svc.Name
    "Service {0} is {1}" -f $svc.Name, $svc.Status



    Remove-Variable logFile -ErrorAction SilentlyContinue
    $logFile = 'C:\LogFile.ps1'
    $logFile | gm
    # identify whether $logFile contains the text C:
    $logFile.Contains("C:") 

    $logFile.Replace("C:","D:") 


    # insert the text \MyScript at character 7
    $logFile.Insert(2,"\MyScript") 
    # that the value stored in $logFile has not changed
    $logFile 

    # update the value of $logFile
    $logFile=$logFile.Insert(2,"\MyScript") 
    $logFile



#endregion:

#region: Date
    $date1 = Get-Date
    $date1
    $date1 | Get-Member
    $date1.Day
    $date1.ToShortDateString()
    $date1.ToShortTimeString()
    $date1.AddDays(3)
    $date1.AddDays(-3)

    Get-Date -Format 'yyyy-MM-dd'
    (Get-Date).ToUniversalTime()
    Get-Date -Format 'HH:mm'



#endregion:

#region: Array
    Remove-Variable arr
    $arr = "aaa", "bbb", "ccc", "ddd","aaa", "bbb", "ccc", "ddd"
    $arr.GetType()
    $arr.length
    $arr[0]
    $arr[3]
    $arr[4]
    $arr[$arr.length -1]
    $arr[-1]
    $arr = $arr + "xxx"
    $arr += "yyy"
    $arr


    # Enumerate the whole array
    for ($i=0; $i -le ($arr.length -1); $i++) {
        $arr[$i]
    }

    Remove-Variable arr
    $arr = "aaa", "bbb", "ccc", "ddd"
    1..10000 | foreach {
        $arr += $_ 
        $arr[-1]
    }

    # !!!
    Remove-Variable arr
    $arr = "xxx", "yyy"
    $arr += "zzz"
    $arr
    $arr.GetType()

    Remove-Variable arr
    [array]$arr = "xxx", "yyy"        # strong typing
    $arr += "zzz"
    $arr
    $arr.GetType()

    Remove-Variable arr
    $arr = @("xxx", "yyy")            # type casting
    $arr += "zzz"
    $arr
    $arr.GetType()

    $arr = @('xxx')
    $arr += 'yyy'

    Remove-Variable arr
    $arr = "line"
    $arr.GetType()
    $arr[0]
    $arr.Length

    Remove-Variable arr2
    $arr2 = "aaa"
    $arr2.GetType()           # String
    $arr2 += "bbbb"
    $arr2
    $arr2.GetType()           # String

    Remove-Variable arr3
    [array]$arr3 = "aaa"      # (strongtyping)
    $arr3.GetType()           # Array
    $arr3 += "bbbb"
    $arr3

    Remove-Variable arr4
    $arr4 = @("aaa","ccc",'dad')
    $arr4.GetType()           # Array
    $arr4 -eq "aaa"           # aaa
    $arr4 -eq "bbb"           #
    $arr4 -like "*a*"         # aaa, dad
    $arr4 -contains "aaa"     # True
    $arr4 -contains "a"       # False
    $arr4 -contains "bbb"     # False


    # Get-Member
    Remove-Variable arr
    $arr
    $arr.GetType()
    $arr = "aaa",222, 81.4, $true  # String, Int32, Double, Boolean
    $arr.GetType()
    $arr | Get-Member            # Get members of the Items in the Array
    Get-Member -InputObject $arr # Get members of the Array

#endregion

#region: ArrayList

    # ArrayList uses more memoryblocks; preferred when frequently modified

    Remove-Variable arr5
    $arr5 = @()   # prep for filling in loop later
    $arr5.GetType()
    $arr5 += "aaa"
    $arr5 += "bbb"
    $arr5 
    $arr5.length
    $arr5.Count
    $arr5 | Get-Member
    Get-Member -InputObject $arr5
    $arr5 -contains "aaa"

    $arr5.Add("ccc")

    Remove-Variable arrList6
    [System.Collections.arrListayList]$arrList6 = "111","222"  # Dynamic Size
    $arrList6.GetType()
    $arrList6.Add("333")
    $arrList6.Add("444")
    $arrList6
    $arrList6[2]
    $arrList6.Remove("333")
    $arrList6

    Remove-Variable arrList7, arrList8
    $arrList7 = "A", "B"
    $arrList8 = "C", "D"
    $arrList7 = $arrList7 + $arrList8
    $arrList7 += $arrList8
    $arrList7


#endregion:

#region: Dynamic Variable Names

    # Set-Variable -Name "$prf$Letter" -Value (Get-Variable -Name "$prf$Letter" -ValueOnly)

    # Problem: Create variable with dynamic name
    $userName = 'Anna'
    $pass     = 'Pa55w.rd'
    # $passAnna ==> Pa55w.rd
    $"pass$userName" = $pass                           # ERROR



    # Solution 1
    Invoke-Expression "`$pass$userName = '$pass'"

    # Solution 2
    New-Variable -Name "pass$userName" -Value $pass
    $passAnna




    $passwordLength = 12
    $password = $null
    $prf = 'User'


    For($a=1; $a -le 5; $a++) {
        $password = $null
        For($i=1; $i -le $passwordLength; $i++) {
            # Generate a random password (12 characters)
            $number = Get-Random -Minimum 65 -Maximum 90
            $letter = [char]$number
            $password += $letter
        }
        if (Get-Variable -Name "$prf$Letter" -ErrorAction SilentlyContinue){
            $a -= 1
        }
        # Define dynamic variables
        Set-Variable -Name "$prf$Letter" -Value $Password

    }
    Get-Variable -Name "$prf*"

    $prf

    Remove-Variable user*, prf, letter, password, passwordLength, a, i, number


    # =====

    Function Test {
        param ($x)

        New-Variable -Name $("Var$x") -Value "xxxxx"
        $Condition = "(`$Var$x -eq 'xxxxx')"
        if (Invoke-Expression $Condition) {
            Write-Host "$((Get-Variable "Var$x").Name) = $((Get-Variable "Var$x").Value)"
        }
    }
    $str = "ABC"
    Test $str


#endregion:

#region: Variable Scopes

    start 'https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_scopes'

    Function SetName {

        $var = 'Function'
        
        Write-Host $local:var  -f Cyan
        Write-Host $global:var -f Yellow

    }

    $var = 'Global'
    SetName
    $var

    ###

    Function SetName {

        $global:var = 'Local'
        
        Write-Host $local:var  -f Cyan
        Write-Host $global:var -f Yellow

    }

    $var = 'Global'
    SetName
    $var


#endregion:

#region: Environment Variables

    $env:USERNAME
    $env:COMPUTERNAME
    Set-Location env:
    dir
    sl C:
    gci env:* -Recurse



#endregion:

#region: Validate value

    # Validate value
     
    [ipaddress]$ip = Read-Host 'Enter IP address'

    [ValidateRange(0, 10)][int]$n = Read-Host 'Enter a number from 0-10'


    [ValidateSet("ca", "eu", "us")]$region = Read-Host 'Enter countrycode'


#endregion