PowerShell Variables Tutorials

As a PowerShell developer, you should know how to use variables. Variables in PowerShell are used to store values that can be easily referenced and manipulated throughout your scripts. You will learn everything about PowerShell variables and various PowerShell variable tutorials here.

What is a Variable in PowerShell?

A variable is a storage location paired with a symbolic name (an identifier) that contains some known or unknown quantity of information referred to as a value. In PowerShell, variables store data that can be used and manipulated throughout a script.

Create and Use Variables in PowerShell

In PowerShell, variable names begin with a dollar sign ($). Variable names are not case-sensitive, so $Variable and $variable are considered the same. Here’s a basic example:

$greeting = "Hello, World!"
Write-Output $greeting

In this example, the variable $greeting is assigned the string value "Hello, World!". The Write-Output cmdlet is then used to print the value of $greeting.

Types of Variables in PowerShell

PowerShell variables can store different data types, including strings, integers, arrays, and even objects. Here are some examples of different types of variables:

  • String Variables

Here is an example of a string variable in PowerShell.

$name = "John Doe"
Write-Output $name
  • Integer Variables

Here is an example of an integer variable in PowerShell.

$age = 30
Write-Output $age
  • Array Variables

Here is an example of an array variable in PowerShell.

$colors = @("Red", "Green", "Blue")
Write-Output $colors
  • Object Variables

Here is an example of an object variable in PowerShell.

$person = New-Object PSObject -Property @{
    FirstName = "John"
    LastName  = "Doe"
    Age       = 30
}
Write-Output $person

Check out PowerShell Variable Naming Conventions

PowerShell Variable Scopes

Variables in PowerShell have different scopes that determine their visibility and lifetime. The main scopes in PowerShell are:

  • Global: Variables are available throughout the entire PowerShell session.
  • Local: Variables are available only within the current script or function.
  • Script: Variables are available within the current script.
  • Private: Variables are available only within the current scope.

Here’s an example to explain PowerShell variable scopes:

$Global:globalVar = "I am global"
$Script:scriptVar = "I am script-level"
$Local:localVar = "I am local"
$Private:privateVar = "I am private"

function Test-Scopes {
    Write-Output $globalVar
    Write-Output $scriptVar
    Write-Output $localVar
    Write-Output $privateVar
}

Test-Scopes

I executed the above PowerShell script, and you can see the output in the screenshot below:

PowerShell Variable Scopes

Special Variables in PowerShell

PowerShell also includes several special variables that have specific purposes. Some of the most commonly used special variables include:

  • $_: Represents the current object in the pipeline.
  • $?: Indicates the success or failure of the last operation.
  • $null: Represents a null value.
  • $PSVersionTable: Contains details about the PowerShell version.

Here’s an example using the $_ variable:

Get-Process | Where-Object { $_.CPU -gt 100 }

In this example, $_ represents each process object passed through the pipeline, and the Where-Object cmdlet filters processes where the CPU usage is greater than 100.

Best Practices for Using Variables in PowerShell

Here are some best practices to follow when using variables in PowerShell:

  1. Use Meaningful Names: Choose variable names that clearly describe their purpose.
  2. Avoid Global Variables: Minimize the use of global variables to reduce the risk of conflicts and unintended side effects.
  3. Initialize Variables: Always initialize variables before using them to avoid unexpected behavior.
  4. Use Consistent Naming Conventions: Follow a consistent naming convention for variables to improve code readability.

PowerShell Variable Naming Conventions

Here are the naming conventions for PowerShell variables.

  • Alphanumeric and Underscore: Variable names should use only letters, numbers, and underscores. Special characters and spaces are not allowed.
    • Example$userName$file_path$count123
  • Descriptive and Concise: Choose variable names that clearly describe their purpose but are not overly long. This helps others (and yourself) understand the code more easily.
    • Example: Instead of $x, use $totalSales if the variable holds the total sales amount.
  • PascalCase: This naming convention capitalizes the first letter of each word without spaces or underscores. It is often used for parameter names and sometimes for variables.
    • Example$TotalSalesAmount$UserName$FilePath
  • camelCase: In camelCase, the first letter of the first word is lowercase, and the first letter of each subsequent word is uppercase. This is commonly used for local variables.
    • Example$totalSalesAmount$userName$filePath
  • Dollar Sign Prefix: All PowerShell variable names must start with a dollar sign ($). This is a syntax requirement in PowerShell.
    • Example$variableName$userAge$isComplete
  • Consistency: Use the same naming convention throughout your script to make it easier to read and maintain. Consistency helps avoid confusion and potential errors.
    • Example: If you start using camelCase for variables, stick with it for all variables in the script:
$userName = "JohnDoe"
$userAge = 30
$isComplete = $false

PowerShell Variables Tutorials

Here are the list of tutorials on variables in PowerShell.

Basics

TutorialDescription
PowerShell New-Variable CmdletHow to create variables using the New-Variable cmdlet and when to prefer it over direct assignment.
PowerShell Print VariableDifferent ways to output variable values to the console, logs, or files using cmdlets like Write-Output and Write-Host.
Output Variables in PowerShellTechniques for returning variables from scripts and functions, including pipeline output and return values.
How to Set Variables in PowerShell?Core methods to declare and assign variables, including direct assignment and Set-Variable usage.
How to Get the Type of a Variable in PowerShell?How to inspect and understand the data type of a variable using .GetType() and type literals.
Remove All Variables From Memory In PowershellApproaches to remove variables from the current session and clean up memory using Remove-Variable.
How to Increment A Variable in PowerShell?Patterns for incrementing numeric variables with operators like += and arithmetic expressions.
Reset Variables in PowerShellOptions to reset variables to defaults or $null without deleting them.
How to Clear Variables in PowerShell?Ways to clear variable contents while keeping the variable name available for reuse.
PowerShell If Variable EqualsWriting if conditions that compare variable values, including strings and numbers.
PowerShell If Variable ContainsChecking whether variables contain specific substrings or values in conditional logic.
PowerShell If Null Then EmptyHandling null values by converting them to empty strings or defaults in your scripts.

Strings and string-based variables

TutorialDescription
How to Increment a String Variable by 1 in PowerShell?How to treat numbers stored as strings and increment them safely.
How to Trim Variable Length in PowerShell?Techniques for shortening strings to a specific length using methods like Substring.
How to Trim Variable Before Character in PowerShell?Removing text before a given character using string operations or splitting.
How to Trim Variable After Character in PowerShell?Removing text after a given character using substring or split logic.
How to Trim the First 4 Characters from a Variable in PowerShell?Examples of dropping a fixed number of characters from the start of a string.
How to Trim the Last 4 Characters from a Variable in PowerShell?Examples of removing a fixed number of characters from the end of a string.
PowerShell Variables in QuotesHow variables behave differently inside single and double quotes and how expansion works.
How to Escape Special Characters in Variables in PowerShell?Approaches for safely handling special characters in variable values, including escape sequences.
Convert GUID to Hex in PowerShell (4 Methods with Examples)Methods for converting GUID values to hexadecimal strings using PowerShell.
How to Convert Spaces to New Lines using PowerShellTransforming text by replacing spaces with newline characters using string and regex operations.

Environment variables

TutorialDescription
How to Set and Get Environment Variables in PowerShell?Creating, reading, and updating environment variables using the Env: drive and .NET.
How to Remove Environment Variables in PowerShell?Safely removing environment variables from user or machine scopes.

Scopes, special, and advanced variables

TutorialDescription
PowerShell Pipeline VariablesUsing pipeline-related variables like $_ to work with objects flowing through the pipeline.
How to Check if a Variable is Null in PowerShell?Different patterns for checking whether variables hold $null values in conditions.
How to Set a Variable to Null in PowerShell?Explicitly resetting variables to $null and scenarios where this is useful.
How to Create Variables with Multiple Values in PowerShell?Creating arrays and collections to store multiple values in a single variable.
How to Share Variables Between Functions in PowerShell?Options like scope modifiers, parameters, and return values to share data between functions.
How to Check if a Variable Exists in PowerShell?Verifying whether a variable is defined using Get-Variable and conditional checks.
How to Check if a Variable is Empty in PowerShell?Distinguishing between null, empty strings, and empty collections in variables.
PowerShell Reference VariablesUsing reference parameters and variables to pass values by reference.
PowerShell Error VariablesWorking with automatic error-related variables such as $Error for troubleshooting.
PowerShell Static VariablesAccessing static properties and fields from .NET types as variables in PowerShell.
PowerShell Global VariablesManaging variables in the Global: scope and understanding their impact.
PowerShell Local VariablesWorking with Local: scope to limit variable visibility to functions or scripts.
PowerShell Private VariablesUsing Private: scope to hide variables within the current scope for encapsulation.

Input, output, and formatting

TutorialDescription
How to Prompt for Variable in PowerShell?Prompting users for input with Read-Host and storing the results in variables.
How to Create an HTML Table from Variables in PowerShell?Building HTML tables from variable data for reports, emails, and dashboards.
Generate Random Numbers in PowerShellGenerating random numbers with Get-Random for testing and script logic.

Conclusion

I hope you now know how to use PowerShell variables. I have explained here:

  • Create and Use Variables in PowerShell
  • Types of Variables in PowerShell
  • PowerShell Variable Scopes
  • Special Variables in PowerShell
  • Best Practices for Using Variables in PowerShell
  • PowerShell Variable Naming Conventions
  • Various PowerShell variable tutorials
100 PowerShell cmdlets download free

100 POWERSHELL CMDLETS E-BOOK

FREE Download an eBook that contains 100 PowerShell cmdlets with complete script and examples.