Variables in PowerShell

Introduction: Windows PowerShell’s variables hold any type of values while executing the commands. The variables store the result from a command, function, and expression. Variables are declared using $ sign before the variable name. Ex. $age, $date_of_birth.

How to Define PowerShell Variables: PowerShell variables can be defined as below

  1. Define and assign value: $age = 18
  2. Store value returned from function: $getDate = Get-Date
  3. Store collections returned from function: $getAllVerbs = Get-Verbs

How to Display PowerShell Variables values: Open the PowerShell. Type all the statements defined above. Just type the name of the variable to print the value. Below are the examples.

  1. $age
  2. $getDate
  3. $getAllVerbs

Types of Variables in PowerShell: PowerShell variables are independent of the type which means any type of value can be stored to a variable. The type of a variable is determined according to .Net Framework type and value assigned.

PowerShell also supports to define the specific type of a variable (int, string) so only that type of value can be stored. How to create specific type variable and store the value is shown below.

VARIABLE: Drive: The Variable: drive is a way to access all the variables in a PowerShell session. We can access the variable in the same way we access the file in the file system drive.

Set-Location command is used to change the Variable: Drive and Get-ChildItem displays all the variables in the PowerShell session. The output of the command Get-ChildItem is not shown due to the number of the Variables in a PowerShell session.

To get specific variable value from the Variable: Drive, we can use the below command.

Variable: CmdLets: PowerShell supports some valuable commands to manage variables. These commands are New-Variable, Get-Variable, Set-Variable, Clear-Variable and Remove-Variable. These CmdLets’s example is shown below. Use Get-Help to get complete details about Variable CmdLets.

Conclusion: Any scripting or programming language usages variables extensively and having better understanding of defining the variables and its type, increases the readability, avoids run time errors and reduces the maintainability of code.

Leave a Reply

Up ↑

%d bloggers like this: