Home ยป PowerShell Variables

PowerShell Variables

PowerShell variable is a placeholder used to store all types of values in it. It can hold different types of data such as strings, integers, results of commands, arrays, or objects.

Variables in PowerShell start with the dollar sign ($) followed by the variable name. They are not case-sensitive.

Here’s a basic example of how to create and use variables in PowerShell.

# Assigning integer to a variable
$number = 241
Write-Host $number

# Assigning a string to a variable
$name = "ActiveDirectoryTools"

Write-Host "Hello, $name!"

# Assigning an array to a variable

$languages = @("Python","PowerShell,"Rust")
Write-Host "My favorite language is $($languages[1])."

# Assigning an object to a variable
$resource = [PSCustomObject]@{
Name = "Gary"
Age = 34
}

Write-Host "$($resource.Name) is $($resource.Age) years old."

# Check the type of variable
$name.GetType()

In this example,

  • $number, $name, $languages and $resource are variables.
  • $number stores an integer, $name stores a string, $languages stores an array, and $resource stores an object.
  • Write-Host cmdlet is used to output variable value to the console.
  • PowerShell automatically detects the type of the variable and converts it to appropriate type. You can check the type of the variable using GetType() method.

Cool Tip: How to Create Read-Only Variables using PowerShell!

Conclusion

I hope the above article on how to create and use PowerShell variables is helpful to you.

You can find more topics about Active Directory tools and PowerShell basics on the ActiveDirectoryTools home page.