Powershell: Variables and Arrays

  PowerShell, Programming

Powershell Variables

Variables

Variable Objects

All variables are Objects

 

Variable declaration: $VarName

Note: These are NOT case sensitive! $MyVar is the same as $myvar

Static variables (aka read-only constants):

  • $true (True, 1)
  • $false (False, 0)

Note: You cannot assign variable to to True or False. Use their variable names.

Get Variable type

Note: Here we’re invoking a method of the variable object as shown later.

> $MyVar = "This is my variable."
> $MyVar.GetType()
IsPublic IsSerial Name        BaseType
-------- -------- ----        --------
True     True     String      System.Object

>$MyVar.Length #Notice this is a property and not a method()
20


> $MyVar = 5
> $MyVar.GetType()
IsPublic IsSerial Name       BaseType
-------- -------- ----       --------
True     True     Int32      System.ValueType

> $MyVar = 5.3
> $MyVar.GetType()
IsPublic IsSerial Name       BaseType
-------- -------- ----       --------
True     True     Double     System.ValueType

To get all of the properties of an Object

$MyVar | Select-Object -Property *

To find the methods available:

Get-Member -InputObject $MyVar

Note: This shows all the available methods and properties! Very Cool!

 

Arrays

Declare an array

> $MyArray = @('str1','str2','str3')
> $MyArray
str1
str2
str3

> $MyArray.GetType()
IsPublic IsSerial Name       BaseType 
-------- -------- ----       -------- 
True     True     Object[]   System.Array

Array Indexes

Indexes start at 0

> $MyArray[1]
str2

Append a new element to an array

$MyArray += 'str4'

Array Key=>Value pairs (These are called ‘Hash Tables’ or ‘Mappings’)

  • Use brackets ‘{..}’ instead of ‘( )’.
  • Use a semicolon ‘;’ instead of commas ‘,’ to separate values.
> $MyArray = @{key1 = 'value1'; 'key2' = 'value2'}
> $MyArray
Name     Value
----     -----
key1     value1
key2     value2

Note: Does not appear that quotes are required around the keys when defining, however, I’d recommend using them as are required with other languages.

View Values

> $myArray.'key1'
value1
> $myArray['key2']
value2

Append a new index

> $myArray.Add('NewKey','NewValue')

Edit a value

> $myArray.Set_Item('NewKey','DifferentValue')
> $myArray['NewKey']='DifferentValue'

Note you must use quotes around the keys.

Removing an array index (element)

> $myArray.Remove("key1")
> $myArray
Name     Value
----     -----
key2     value2
NewValue DifferentValue

LEAVE A COMMENT