Variables and Types

Like any other scripting language, PowerShell also provides ability to declare variables with it's type. But in PowerShell we can declare variable without specifying any data type, and it can be used to store values of any type e.g. integer, string, boolean, decimal etc. It can also store object e.g. result of any command.

In Windows PowerShell variables can be declared with the $ prefixed e.g. $age, $firstName $city etc. Infact no need to declare any variable, you can directly start using any variable starting with $.

In Windows PowerShell variable names must starts with $ and can contain alphanumeric, underscore, special characters etc. Variable names with special character must be enclosed in {}. Variable names are not case-sensitive in Windows PowerShell. Default value of any variable is $null if you have not assigned any.

Example
$age = 10;                   	  # full number example
$amount = 23.45;                  # decimal number example
$name = "Tutorials Corner";       # string example
$isDay = $true;               	  # boolean example

$age;
$amount;
$name;
$isDay;

Some notes about the PowerShell types.

If you run above statements directly it will show value of all variables. Notice that we don't need to declare any variable before using in Windows PowerShell, variables will be created in memory automatically according to values assigned to those variables.

If you want to find the type of any variable then you can use GetType() method of any variable e.g. if we do $age.GetType() then it will return

Example
IsPublic	IsSerial	Name		BaseType
--------	--------	----		-------- 
True		True		Int32		System.ValueType

Also, notice that $ sign with true, here $true and $false are constants. There are no language-level literals for booleans. In number it can hold integer number or decimal number. String type of variable can store any type of string.

# (HASH Sign) can be used for single line comment in Windows PowerShell, and <# .... #> can be used for multi line comment e.g.

Example
<# Below statements are to show how
variables and types work in PowerShell#>
$age = 10;                   	  # full number example
$amount = 23.45;                  # decimal number example

$age;
$amount;

You can specify scope while using a variable, there are three types of scope. Let's go through those one by one.

  • Global: As name suggest, these variables are global variables, which can be used outside script or function.
  • Local: If you don't specify scope then by default variables are local variables which can be used in script or function only.
  • Script: If variables are defined script variable then those variables can be used within that script only.

 

← Previous

Next →