EDUCBA

EDUCBA

MENUMENU
  • Free Tutorials
  • Free Courses
  • Certification Courses
  • 360+ Courses All in One Bundle
  • Login

Variable in PowerShell

By Priya PedamkarPriya Pedamkar

Home » Data Science » Data Science Tutorials » PowerShell Tutorial » Variable in PowerShell

Variable-in-PowerShell

Introduction to Variable in PowerShell

The variable in PowerShell is a block of memory that can be used to store values. PowerShell variables are denoted using the “$” symbol. A variable name can be anything from numbers, alphabets or even underscores. PowerShell variables are not case sensitive. PowerShell variables are not just text-based, instead, they are objects like that of Microsoft.Net objects.

Creation of Variables with Syntax

The below example shows the creation of a variable

Start Your Free Data Science Course

Hadoop, Data Science, Statistics & others

$test

$test is a variable and it can be assigned a value using the = or assignment operator

$test=” This is a variable”

To get the value of a variable, we just need to simply enter the variable

Example #1

The following example is used to show introduction to variable

Code:

Write-Host "Introduction to the variable"
$test="This is a variable"
Write-Host "The value of the variable is below"
$test

Output:

Introduction to variable

The value of the variable is below

This is a variable

Example #2

The following example is used to show arithmetic operations on a variable

Popular Course in this category
Sale
Programming Languages Training (41 Courses, 13+ Projects, 4 Quizzes)41 Online Courses | 13 Hands-on Projects | 322+ Hours | Verifiable Certificate of Completion | Lifetime Access | 4 Quizzes with Solutions
4.5 (9,275 ratings)
Course Price

View Course

Related Courses
Shell Scripting Training (4 Courses, 1 Project)All in One Data Science Bundle (360+ Courses, 50+ projects)Data Visualization Training (15 Courses, 5+ Projects)

Code:

Write-Host "Example of arithmetic operation"
$v1 = 11111
$v2 = 3333454
$v3 = $v1 + $v2
$v3

Output:

Example of arithmetic operation

3344565

Variable Types in PowerShell

In PowerShell, if the datatype of the variable is not specified, PowerShell automatically detects the variable type when the variable is initialized.

The following are the types of the array variable

1. Array: An array variable is the first type of variable. An array variable can be declared as follows

[int32[]]$inttest = 1,2,3,4

or

$test=1..99

2. Bool: A Boolean variable can be defined as follows.

[bool] $test = 1
Or

[bool] $test= $true

3. DateTime: A datetime variable can be declared as follows

$a = [DateTime] "07/06/2015 05:00 AM"

4. Guid: A guid value can be assigned to a variable as follows

$a=New-Guid

5. HashTable: The hashtable variable is storing a key-value pair. A hashtable can be defined as follows

$test = @{ key1= 1; key2= 2; key3= 3}

or

$test = @{}

6. PSObject: A PSobject variable is similar to the hashtable and uses a key-value pair structure. It can be defined as follows.

$test = [PSCustomObject]@{
Key1 = 'Value1'
Key2 = 'Value2'
}

Automatic Variables in PowerShell

These variables are created by PowerShell itself. They are used to maintain the state of the PowerShell. Users will not change the value of these variables and PowerShell changes them to maintain accuracy. The following are some of the automatic variables.

Variable Description
$HOME Contains the path of the user’s home directory
$HOST Represent the application for PowerShell
$NULL Null Value
$PROFILE Represents the full path of the current user profile
$STACKTRACE Contains the stack trace of the recent error
$PSCOMMANDPATH Contains the path of the running script
$PID Contains the processor id of the current session
$ErrorActionPreference Represents the action taken when an error message is delivered
$PSCulture Represents the current culture of the Powershell session

All the automatic variable is PowerShell can be found by running the below command.

Code:

Get-Variable

Output:

variable in powershell

variable in powershell

Different Types of Variable Scopes

The scope is nothing but the life shell of a variable. A variable is alive only within the scope specified.

  • $Global: A variable is available throughout the script in the current session.
  • $Script: The variable is accessible only inside the script and is discarded after the script is finished executing.
  • $Private: Variable is valid only within a function.
  • $local: Variable is valid only in the current scope of the session.
  • Cmdlets associated with variables:
  • Clear-Variable: Deletes the value of a variable
  • Get-Variable: Gets the list of variables that are present in the current session.
  • New-Variable: Used to create a new variable
  • Remove-Variable: Deletes the variable
  • Set-Variable: Used to change the value of a variable

Examples #1

To check if the last ran cmdlet was successful or not.

Code:

$? is used for the above-said purpose

The previous cmdlet ran

get-mynae

Corresponding output

variable in powershell

As it is evident from the above, the cmdlet execution was unsuccessful. After that, the cmdlet was executed.

Code

$?

Output:

variable in powershell

windows system

False denotes the last cmdlet was unsuccessful and true denotes successful execution.

Example #2

To Store the value of a variable to a word or csv file

Code:

Write-Host "variable example"
$test = "First variable"
$test1 = "second variable"
$test2 = "third variable"
$test3 = "fourth variable"
$test | Out-File C:\test.txt -Append
$test1 | Out-File C:\test.txt -Append
$test2 | Out-File C:\test.txt -Append
$test3 | Out-File C:\test.txt -Append

Output:

test notepad

Example #3

Set and Get a Variable

Code:

Set-Variable -Name "test" -Value "test"
Get-Variable -Name "test"
Set-Variable -Name "test1" -Value "testone"
Get-Variable -Name "test1"
Set-Variable -Name "test2" -Value "testtwo"
Get-Variable -Name "test2"
Write-Host "Get all the user defined variables in the current session"
Get-Variable test* -ValueOnly

Output:

name value

Conclusion

Thus, the articles covered in detail about variables in PowerShell. It also explained the data types associated with a variable, variable scope and the types of variables that are available in PowerShell. To understand much deeper about variables it is advisable to create sample programs and have fun working around them.

Recommended Articles

This is a guide to Variable in PowerShell. Here we discuss how to create variables, different Types of Variable Scopes and automatic variables in PowerShell along with the examples. You can also go through our other suggested articles to learn more–

  1. PowerShell Move-Item
  2. Get-Command in PowerShell
  3. Comparison Operators in PowerShell
  4. Loops in PowerShell
  5. PowerShell Out-File | Examples and Parameters

Programming Languages Training (41 Courses, 13+ Projects)

41 Online Courses

13 Hands-on Projects

322+ Hours

Verifiable Certificate of Completion

Lifetime Access

4 Quizzes with Solutions

Learn More

0 Shares
Share
Tweet
Share
Primary Sidebar
PowerShell Tutorial
  • Basics
    • PowerShell comment
    • PowerShell Map Network Drive
    • PowerShell Append to File
    • PowerShell print
    • What is PowerShell
    • Uses Of Powershell
    • PowerShell Versions
    • How To Install PowerShell
    • PowerShell uninstall module
    • How to Use PowerShell?
    • PowerShell Logging
    • PowerShell Tools
    • PowerShell Commands
    • PowerShell Administrator
    • PowerShell Modules
    • PowerShell Registry
    • PowerShell block Comment
    • PowerShell Verbs
    • PowerShell list
    • PowerShell add user to group
    • PowerShell Write to Console
    • Variable in PowerShell
    • PowerShell New Line
    • PowerShell prompt for input
    • PowerShell File Extension
    • Powershell Remotesigned
    • PowerShell Write to File
    • PowerShell Ping
    • PowerShell wget
    • PowerShell Global variable
    • PowerShell Get-ADGroup
    • Array in PowerShell
    • PowerShell Multidimensional Array
    • PowerShell Array of Strings
    • PowerShell? join array
    • Useful PowerShell Scripts
    • String in PowerShell
    • PowerShell Switch Statement
    • PowerShell Function Parameters
    • PowerShell vs PowerShell ISE
    • PowerShell test-connection
    • PowerShell Test-NetConnection
    • PowerShell GUI
    • PowerShell Variable in String
    • PowerShell Active Directory
  • Variables
    • PowerShell Variables
    • PowerShell Environment Variables
    • PowerShell set environment variable
    • Hashtable in PowerShell
    • Set Variable in PowerShell
  • Operators
    • PowerShell Operators
    • Comparison Operators in PowerShell
    • Logical Operators in PowerShell
    • PowerShell Boolean
    • PowerShell Like Operator
  • cmdlet
    • PowerShell Wait
    • PowerShell Match
    • cmdlets in PowerShell
    • Start PowerShell from cmd
    • Add-Content in PowerShell
    • Get Help in PowerShell
    • PowerShell Copy-Item
    • PowerShell Remove-Item
    • PowerShell Move-Item
    • Get Command in PowerShell
    • PowerShell Run Command
    • Windows PowerShell ISE
    • Windows Powershell Commands
    • WinRM PowerShell
    • PowerShell Date
    • Powershell Write-Host
    • PowerShell Get-ChildItem
    • PowerShell Sort-Object
    • PowerShell Where Object
    • PowerShell Set-Content
    • PowerShell Set-Location
    • PowerShell Invoke-Command
    • PowerShell Invoke-Webrequest
    • PowerShell Get-Location
    • PowerShell Get-Date
    • PowerShell Get-Service
    • PowerShell Test-Path
    • Powershell Module Path
    • PowerShell Out-File
    • PowerShell if File Exists
    • Powershell Copy File
    • PowerShell Delete File
    • PowerShell New-Item
    • PowerShell Rename-Item
    • PowerShell ComputerName
    • PowerShell Get-Content
    • PowerShell Get-Item
    • PowerShell Get-ADUser
    • PowerShell Grep
    • PowerShell Concatenate String
    • PowerShell Get-Process
    • PowerShell Count
    • PowerShell pause
  • Control Statements
    • If Statement in PowerShell
    • If Else in PowerShell
    • Else If in PowerShell
    • Loops in PowerShell
    • For loop in PowerShell
    • PowerShell While Loop
    • PowerShell do while
    • PowerShell Loop through Array
    • PowerShell add to array
    • PowerShell ForEach Loop
    • PowerShell Break
    • PowerShell Continue
    • Switch Case in PowerShell
    • PowerShell If-Not
    • Try-catch in PowerShell
  • Functions
    • PowerShell Functions
    • PowerShell String Functions
    • powershell nslookup
    • PowerShell here string
    • PowerShell Wildcards
    • Regex in PowerShell
    • PowerShell not like
    • PowerShell Filter
    • PowerShell Sleep
    • PowerShell where
    • PowerShell join string
    • PowerShell Exit
    • PowerShell null
    • PowerShell Dictionary
    • PowerShell Location
    • PowerShell Trim
    • PowerShell Join-Path
    • PowerShell Execution Policy
    • PowerShell SubString
    • PowerShell Format Table
    • PowerShell Import Module
    • PowerShell ForEach Object
    • PowerShell Alias
    • PowerShell Scheduled Task
    • PowerShell Convert String to Date
    • PowerShell Split String
    • PowerShell Multiline String
    • PowerShell MultiLine Comment
    • PowerShell Rename Folder
    • PowerShell Delete Folder
    • PowerShell String Replace
    • PowerShell join
    • PowerShell xcopy
    • PowerShell Base64
    • PowerShell Tail
    • PowerShell User List
    • PowerShell remove User from group
    • PowerShell JSON Format
    • PowerShell Send Mail
    • PowerShell Convert to String
    • PowerShell Start-Process
    • PowerShell change directory
    • PowerShell Open File
    • PowerShell Batch File
    • PowerShell ZIP
    • PowerShell unzip
    • PowerShell XML
    • PowerShell XML Parsing
    • Remote PowerShell
    • PowerShell Escape Character
    • PowerShell scriptblock
    • PowerShell Executable Location
    • PowerShell Import-CSV?
    • PowerShell Export CSV
  • Interview Questions
    • PowerShell Interview Questions

Related Courses

Shell Scripting Course

All in One Data Science Courses

Data Visualization Courses

Footer
About Us
  • Blog
  • Who is EDUCBA?
  • Sign Up
  • Live Classes
  • Corporate Training
  • Certificate from Top Institutions
  • Contact Us
  • Verifiable Certificate
  • Reviews
  • Terms and Conditions
  • Privacy Policy
  •  
Apps
  • iPhone & iPad
  • Android
Resources
  • Free Courses
  • Database Management
  • Machine Learning
  • All Tutorials
Certification Courses
  • All Courses
  • Data Science Course - All in One Bundle
  • Machine Learning Course
  • Hadoop Certification Training
  • Cloud Computing Training Course
  • R Programming Course
  • AWS Training Course
  • SAS Training Course

© 2022 - EDUCBA. ALL RIGHTS RESERVED. THE CERTIFICATION NAMES ARE THE TRADEMARKS OF THEIR RESPECTIVE OWNERS.

EDUCBA
Free Data Science Course

Hadoop, Data Science, Statistics & others

*Please provide your correct email id. Login details for this Free course will be emailed to you

By signing up, you agree to our Terms of Use and Privacy Policy.

EDUCBA
Free Data Science Course

Hadoop, Data Science, Statistics & others

*Please provide your correct email id. Login details for this Free course will be emailed to you

By signing up, you agree to our Terms of Use and Privacy Policy.

Let’s Get Started

By signing up, you agree to our Terms of Use and Privacy Policy.

Loading . . .
Quiz
Question:

Answer:

Quiz Result
Total QuestionsCorrect AnswersWrong AnswersPercentage

Explore 1000+ varieties of Mock tests View more

EDUCBA Login

Forgot Password?

By signing up, you agree to our Terms of Use and Privacy Policy.

This website or its third-party tools use cookies, which are necessary to its functioning and required to achieve the purposes illustrated in the cookie policy. By closing this banner, scrolling this page, clicking a link or continuing to browse otherwise, you agree to our Privacy Policy

EDUCBA

*Please provide your correct email id. Login details for this Free course will be emailed to you

By signing up, you agree to our Terms of Use and Privacy Policy.

Special Offer - Programming Languages Training (41 Courses, 13+ Projects) Learn More