Let’s start with Powershell – part2
Special variables
There are several special variables:
- $true
- $false
- $null
PS H:\> $test=$true PS H:\> $test True
Multiline string variables
PS H:\> $more_lines="First Line, Second Line, Third Line" PS H:\> $more_lines First Line, Second Line, Third Line PS H:\> $more_lines.gettype() IsPublic IsSerial Name BaseType -------- -------- ---- -------- True True String System.Object
Arrays
Arrays are variables with multiple values with the first value indexed as 0, the second as 1 and so on.
PS H:\> $array='First Line','Second Line','Third line' PS H:\> $array First Line Second Line Third line PS H:\> $array.gettype() IsPublic IsSerial Name BaseType -------- -------- ---- -------- True True Object[] System.Array
Each array entry is treated on it’s own and we can ask for every independently.
PS H:\> $array[0] First Line
We can make changes, or just operate on the every one array entry
PS H:\> $array| %{echo "Every line $_"} Every line First Line Every line Second Line Every line Third line
Pipe “|” enables us to transfer every single array entry to another command.
I this case we are only writing string and every array entry ( $_ )
We can also create a new array (or make change to existing one) in the same way
PS H:\> $array2=$array| %{echo "Every line $_"} PS H:\> $array2 Every line First Line Every line Second Line Every line Third line
Arrays of Objects
We use get-childitem (alias dir,ls) command to get the file and folder contents of the current directory but assign the result to $dir_array
In this case we create an array of objects (files,directories)
PS D:\tools> dir Directory: D:\tools Mode LastWriteTime Length Name ---- ------------- ------ ---- d---- 2015-04-15 13:58 Egzams d---- 2015-04-17 12:36 install d---- 2015-04-15 09:47 keepass d---- 2015-04-09 09:23 Mremote d---- 2017-11-07 09:52 scripts d---- 2015-04-15 10:01 SQL d---- 2015-04-15 14:51 sysinternals d---- 2015-04-08 15:07 VPN -a--- 2015-04-07 09:10 398260 coursedescription-SKILLPORT-WS_ICFG_A12_IT_ENUS.pdf ----- 2015-04-29 11:39 169257 WSUS.zip PS D:\tools> $dir_array=dir PS D:\tools> $dir_array[0] Directory: D:\tools Mode LastWriteTime Length Name ---- ------------- ------ ---- d---- 2015-04-15 13:58 Egzams
Hashes
Hashes or dictionary objects are very useful. They are essentially arrays of key-value pairs.
For this example we shall use Names and age.
PS D:\tools> $years=@{"Bartosz" = 39; "Marek" = 41; "Andrzej"=20} PS D:\tools> $years Name Value ---- ----- Marek 41 Andrzej 20 Bartosz 39 PS H:\> $years.Count 3
We can also add something to hashtable
PS D:\tools> $years.Add("Kamil",32) PS D:\tools> $years Name Value ---- ----- Marek 41 Andrzej 20 Kamil 32 Bartosz 39 PS H:\> $years.Count 4
Listing – We can ask for a special value of the object
PS D:\tools> $years.Bartosz 39
Next Page…