Let’s start with Powershell – part2
Removing variables
To remove variable, use command Remove-Variable with the name of the variable (without the $)
PS C:\> $years Name Value ---- ----- Marek 41 Andrzej 20 Kamil 32 Bartosz 39 PS C:\> Remove-Variable years PS C:\> $years PS C:\>
Converting Variables
To change the type of the variable, we need to convert it.
The simplest way is by declaring the new type of the variable
PS H:\> $a="3" PS H:\> $a.gettype() IsPublic IsSerial Name BaseType -------- -------- ---- -------- True True String System.Object PS H:\> $a=[int] $a PS H:\> $a 3 PS H:\> $a.gettype() IsPublic IsSerial Name BaseType -------- -------- ---- -------- True True Int32 System.ValueType PS H:\> $b="HELLO" PS H:\> $b HELLO PS H:\> $b.GetType() IsPublic IsSerial Name BaseType -------- -------- ---- -------- True True String System.Object PS H:\> $b=[int] $b Cannot convert value "HELLO" to type "System.Int32". Error: "Input string was not in a correct format." At line:1 char:1 + $b=[int] $b + ~~~~~~~~~~~ + CategoryInfo : InvalidArgument: (:) [], RuntimeException + FullyQualifiedErrorId : InvalidCastFromStringToInteger
As You can see, we cannot convert word Hello to the Integer 😉
TIP
If you want to create a variable with the defined type and not let it create automatically, you can do it like that:
PS H:\> [array]$a="test" PS H:\> $a.gettype() IsPublic IsSerial Name BaseType -------- -------- ---- -------- True True Object[] System.Array
Methods of the variable
To find out, what kind of methods are available to the variable we need to use get-member (alias gm)
PS H:\> $a="234" PS H:\> $a|gm TypeName: System.String Name MemberType Definition ---- ---------- ---------- Clone Method System.Object Clone(), System.Object ICloneable.Clone() CompareTo Method int CompareTo(System.Object value), int CompareTo(string strB), in... Contains Method bool Contains(string value) ………………
We can also convert this string to the another format using proper method
PS H:\> $b=$a.ToDouble($null) PS H:\> $b.gettype() IsPublic IsSerial Name BaseType -------- -------- ---- -------- True True Double System.ValueType
Exercise
- Create a variable $a and assign it a value of 3 then use the write-host command to display the value.
- Type $a.GetType() to find the type of variable $a
- Create a variable $b and assign it a value of 3.3 then use the write-host command to display the value.
- Type $b.GetType() to find the type of variable $b
- Create a variable $c and assign it a value of “3.3” (include those quotes) then use the write-host command to display the value.
- Type $c.GetType() to find the type of variable $c
- Assign to a variable $d the sum of the first two variables by typing $d=$a + $b
- What value is returned when you convert to integer the values 3.4 and 3.6?
Check last page for the result.