Variables
- Variables
- Define variables
- Read-Host
- Variable Types
- Automatic variables
- Get-Variable
- Scope of variables
- Environment
Define variables
We can store values in variables during running scripts. PowerShell includes many types of variables. You can define a variable with dollar-sign $
. You can show the value of the variable just writing the variable name with $
#this a comment
$a = 4
$b = 5
$c = $a + $b
$name = "Jakke Jäyhä"
You can define a string variable with double quotas "string"
or with single quotas'string'
. You can combine strings using the “+”
operator.
You can show the value of the variable with Write-Host
-command.
You can assign many variables at one line
$fname, $lname,$age = "Jack", "Russell", 42
$fname + " " + $lname, $age
Hint: You can put your string variable directly inside string. It makes easy to concatanate string, so easy and nice :-)
$fname, $lname = "James", "Bond"
Write-Host "My name is $lname, $fname $name"
Read-Host
You can set a variable to user input with cmdlet Read-Host
Please, note that Read-Host returns string or secure-string.
You can read a variable to input from user also as secure string.
Variable Types
The PowerShell variable type is set automatically based on the value you assign to it. You can store any type of object in a variable, including integers, strings, arrays, and hash tables. And, objects that represent processes, services, event logs, and computers.
If needed, you can also assign the type manually using variable type in the front of the variable. The type of the variable can be got with the function GetType()
.
[string]$address = "www.netilla.com"
$address.GetType().Name
PowerShell Variable Types
In the table are some of the PowerShell variable types.
Variable Type | Description | Example |
---|---|---|
string | text string | $a="Jack" |
int | 32-bit integer | $b=313 |
single | 32-bit floating point number | $c=37.3 |
[DateTime] | Date and Time | $mydate=get-date |
[array] | Array of elements (see late) | $nums = 1,2,3,4,5 |
Read more about PowerShell Variable Types
Casting String to Int
Casting
is a programming and scripting term that converts one like object type to another. Not all objects can be cast to one another though.
To get integer from end-users, we must tell PowerShell that user´s input is actually a number by converting the string to an int. We use PowerShell to explicitly cast the string to an integer type using a cast operator [int]
.
$a = Read-Host("Give an integer")
$a = [int]$a
$b = $a + 1
Write-Host("You gave", $a, " and when we add one to it, sum is:", $b)
Casting and Formatting Date and Time
In the following example we will cast a string to datetime-type.
#please note that date must be in US style
$a = "12/24/2021"
$b = [datetime]$a
#without formatting
Write-Host("Santa Claus is coming at", $b.DateTime)
#to short date
Write-Host("Santa Claus is coming at", $b.ToShortDateString())
We can get current date with cmdlet Get-Date
. If we want to seperate day and time from date it is with -Format
option.
$d = Get-Date -Format d
$t = Get-Date -Format t
Write-Host "Tänään on $d ja kello on $t"
In the following example let's use the .NET format specifier. Please, note that with fi-fi culture we have to use big M-letter. Look carefully how it affects to the inputs.
Get-Date -Format "dd.MM"
Get-Date -Format "dd.MM.yy"
Get-Date -Format "dd.M.yy"
Get-Date -Format "dd.MM.yyyy"
Automatic variables
PowerShell has some predefined automatic variables. Here are some examples.
Variable | Description |
---|---|
$_ or $PSItem |
Contains the current object in the pipeline object. You can use this variable in commands that perform an action on every object or on selected objects in a pipeline. |
$HOME | Contains the full path of the user's home directorym typically C:/Users/UserName . This variable is the equivalent of the $env:homedrive$env:homepath Windows environment variables |
$IsLinux, $IsMacos, $IsWindows | Contains $TRUE if the current session is running on a Linux, Macos or Windows operating system, otherwise contains $FALSE. Works only in PowerShell 7. |
$PSUICulture | Contains the name of the user interface (UI) culture that's currently in use in the operating system. |
#run this is your computer with PowerShell7
if ($IsLinux)
{"This is a Linux computer"}
elseif ($IsWindows -eq $true)
{"This is a Windows computer"}
else
{"Nope, this has other OS"}
Look the full list of automatic variables here
Get-Variable
You can get all the variables and their values with the cmdletGet-Variable
. Cmdlet list all the variables, the automatic preset variables and the variables you have been defined. Cool.
Scope of variables
Variables are in different scope depending where they are defined. PowerShell supports the following scopes:
Global: Variables and functions that are present when PowerShell starts have been created in the global scope, such as automatic variables and preference variables. The variables, aliases, and functions in your PowerShell profiles are also created in the global scope. The global scope is the root parent scope in a session.
Local: The current scope. The local scope can be the global scope or any other scope.
Script: The scope that's created while a script file runs. Only the commands in the script run in the script scope. To the commands in a script, the script scope is the local scope.
Scope modifiers
A variable, alias, or function name can include any one of the following optional scope modifiers:
- global: Specifies that the name exists in the Global scope.
- local: Specifies that the name exists in the Local scope. The current scope is always the Local scope.
- private: Specifies that the name is Private and only visible to the current scope.
You can set the scope of the variable like this:
$global:a = "one"
Environment
It is easy to get info about current environment with automatic variable $env
. Here is the example how to use $env
-variable.
The environment variables starting with u-letter can be listed with the following command:
Get-ChildItem -Path Env:\u*