Module 3: Variables, Data Types and Array
Module 3: Variables, Data Types and Array
Variables/Data types:
PowerShell assigns best fit primitive data type for a given value
The process of automatic selection of data type is called “Weekly typed”
Ex: $Course=‘PowerShell’, $Duration=2
Process of specifying the exact type of data to be stored is called “Strongly Typed”
Ex:[String]$Course=‘PowerShell’, [Int32]$Duration=2
<Variable_Name>.GetType().Name – Gives the actual data type of variable
Ex: [Byte]$Flag=12, $Flag.GetType().Name
PS C:\Users\v-bapunn> Remove-Variable a
Option Description
"None" NO option (default)
"ReadOnly” Variable contents may only be modified by means of the -force
parameter
"Constant" Variable contents can't be modified at all. This option must already
be specified when the variable is created. Once specified this option
cannot be changed.
Environment Variables:
“Dir Env:” to view all available environment variables
$Env:Windir, $Env:ComputerName, $Env:UserDomain,Env:UserProfile
$Env:<Name>=<Value> - To Create new environment variable
[environment]::SetEnvironmentvariable("Path", $newValue, "User") to change environment
variable perminantly
Here Strings:
Here string always begins with @’ and ends with ‘@
Here string are useful when you required to provide single quotes and double quotes in
single string
Ex: $s= @'
"Hello world"
"One more line"
‘Get-Process’
Dir
'@
`n New line
`r Carriage return
`a Alarm
`b Backspace
`0 Null
Sub Expressions:
Variable contains an expression
$(Expression) is a variable
$(2+2) is variable with subexpression
“Result=(2+2)” displays “Result=(2+2)”
“Result=$(2+2)” displays “Result=4”
$File=dir d:\PowerShell, $file.Length
“The size of file is ($file.Length)” does not give expected size
“The size of file is $($file.Length)” gives expected size
Get-Member:
An objects properties and methods are referred as its members
Get-Member is the discovery cmdlet
– Alias: gm
Don’t assume that cmdlet output shows all or actual properties
– Some properties are calculated or custom
– PowerShell attempts to be IT Pro friendly
Pipe any command to Get-Member to learn about objects exiting the pipeline
Ordered Hash:
Hash tables are unordered by default
No guarantee what order data will be displayed, Usually not an issue with small hash tables
PowerShell 3.0 introduced [ordered] attribute
$hash=[ordered]@{ A=123; B="foo"; C=3.14 }
Comparison Operators: Used to compare two values.