EDUCBA

EDUCBA

MENUMENU
  • Free Tutorials
  • Free Courses
  • Certification Courses
  • 360+ Courses All in One Bundle
  • Login
Home Data Science Data Science Tutorials PowerShell Tutorial PowerShell Variables
Secondary Sidebar
PowerShell Tutorial
  • Variables
    • PowerShell Variables
    • PowerShell Environment Variables
    • PowerShell set environment variable
    • Hashtable in PowerShell
    • Set Variable in PowerShell
  • Basics
    • PowerShell Restart Service
    • PowerShell comment
    • PowerShell Map Network Drive
    • PowerShell Append to File
    • PowerShell print
    • What is PowerShell
    • Uses Of Powershell
    • PowerShell Empire
    • PowerShell Parameter
    • PowerShell Stop Service
    • PowerShell Versions
    • How To Install PowerShell
    • PowerShell uninstall module
    • How to Use PowerShell?
    • PowerShell Logging
    • PowerShell Tools
    • PowerShell Commands
    • PowerShell Version Command
    • 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
  • 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 Start-Service
    • PowerShell is not digitally signed
    • PowerShell Uptime
    • PowerShell Create Directory
    • 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

PowerShell Variables

By Priya PedamkarPriya Pedamkar

PowerShell Variables

Introduction to Variables in PowerShell

Variables in PowerShell are automatic by default, that means according to your assigned data it will select a data type, for example, if it is $age=1 than it will be int32 and if It is $student =” Ranjan” than it will be a string. Variable in PowerShell starts with $ symbol. Variables in PowerShell are not case sensitive and they may contain any letters, numbers and special characters. In the case of special characters they need to enclose with  {}, for example, ${Ranjan rating out of 10 is}=10. And we can get output from variable ${Ranjan rating out of 10 is} is 10. In the very simple word variable is a placeholder for any important data like any string or any integer. An example in the below screen with variable with special characters.

powershell variables output 1

How to Declare Variables in Powershell?

The variable declaration means, naming a variable with its data type or its basic property. In PowerShell Naming a variable is just informing about the variable to memory. Once we assign something like string or integer, it will be informed to memory about the data type of variable  And according to that, it’s allocation in memory done at that time only.

By declaration, we are informing the system about the variable type and its names only, in the declaration we are not defining memory size needed to hold variable. Memory size needs to hold any variable part is done by the system at the time of initializations.

Start Your Free Data Science Course

Hadoop, Data Science, Statistics & others

PowerShell supports many other data types other than string and integer, such as floating-point numbers, decimal, and Boolean values, etc. You don’t have to explicitly declare the data type of a variable; PowerShell automatically chooses the data type at the time of initialization. PowerShell also provides data type conversion at the time of initialization.

$number ="Ranjan"//string
$number =34//int32
$sum=$number+$number

powershell variables output 2

In PowerShell, we can strictly defined data type for any variables. Below example, we have defined variable strictly so we can only assign those data which are relevant to its data type.

[Int]$number="Ranjan"//throw an error as we defined it as Int and assigning the value of the string
[Int]$number=23

powershell variables output 3

Automatic conversion of the variable in PowerShell. In the below example Initially, we assigned a string and we checked it’s data type we found it was a string and we assigned an integer value and we checked it’s data type and we found it was int32.

$id ="test123"
$id.GetType().Name
$id=78
$id.GetType().Name

powershell variables output 4

How to Initialize Variables in Powershell?

Initialization means telling the system about the size of memory needed to hold the variable as we are initially assigning something. We can initialize our variable according to our further uses.

All in One Data Science Bundle(360+ Courses, 50+ projects)
Python TutorialMachine LearningAWSArtificial Intelligence
TableauR ProgrammingPowerBIDeep Learning
Price
View Courses
360+ Online Courses | 50+ projects | 1500+ Hours | Verifiable Certificates | Lifetime Access
4.7 (86,527 ratings)

For example, each year age is increasing below.

$age =0
$age=$age+1
$age=$age+1
$age=$age+1
$age=$age+1

So on. But if we Initialise like below

$age="zero"
$age=$age+1
$age=$age+1
$age=$age+1
$age=$age+1

powershell variables output 5

Hence we found at the time of initialization we should initialize with integer value or string according to our users in further programming.

Rules and Regulations for Variables in Powershell

Let’s discuss some rules of PowerShell variables. PowerShell variables always start with $ symbol and it can contain a combination of letters, numbers, and underscores. If you really feel it is important to use characters other than this, you have to enclose them in curly braces. You should not use the name of variables that have been pre-defined and try not to assign the string to a strictly int defined variable else it will throw an error.PowerShell has reserved variables such as $$, $?, $^, and $_ that contain alphanumeric and special characters.

Here are examples of valid variable names:

$schoolType, $schoolType_1, ${school-type not known}

Below is some wrong way for variable naming.

schoolName, $school-type, $school type

Note: If we have given any space in the variable name than we have to mention that space in the variable name at the time of accessing that variable.

Example:

Let us look at the example mentioned below:

$schoolId = 1, 2, 3 //assigning array to variable
//Checking it’s data type , we can see it is an Object type
$schoolId.GetType().Name
Object[] $schoolId="ranjan" //assigning string to same variable
//Checking it’s data type , we can see it is a String type
$schoolId.GetType().Name
String
$schoolId=23 //assigning int value to same variable
//Checking its data type, we can see it is a Int32 type
$schoolId.GetType().Name
Int32
$schoolId=FALSE  //wrong way of assignment throw an error
$schoolId=$FALSE //correct way of assignment
//Checking its data type, we can see it is a Boolean type
$schoolId.GetType().Name
Boolean

powershell variables output 6

In the above example, we first assigned array to a variable than string name and then numeric suddenly it throws an error when we assigned FALSE as $FALSE is the correct way to assign any boolean value.

[int]$schoolNumber = 81 //Strictly defining data type of variable to integer
$schoolNumber = "9999" //Here string of numeric will be converted to an integer
$schoolNumber = "zero" //As we have defined integer so we can not assign string

It will throw an error, see in the below screen.

output 7

[string]$words = "Ranjan"
$words = 30       // The integer is converted to a string.
$words += 10     //Treat $words as string only
$words+= 21    //keep concatenate as string
$words+= 31

In the above code block, because we have defined $words as a string so it will not perform any arithmetic operation here it will treat all these variables as a string and concat them as a string. The screens of the above execution are given below.

output 8

Let’s understand Date datatypes in PowerShell,

[datetime] $DOB = "04/11/88"   //It will convert string of date to Date objects.
$DOB

Output: Monday, 11 April, 1988 12:00:00 am

The screen is given below,

output 9

In the above example, we are just passing date as a string variable and PowerShell converts it to date and time object.

Conclusion

To conclude, I hope I was able to explain variables in the simplest way. PowerShell gives a lot of flexibility for variable defining and it provides auto type casting which makes it very powerful and easy to use.

Recommended Articles

This is a guide to PowerShell Variables. Here we discuss how to declare and initialize variables in Powershell along with the rules and regulations. You may also look at the following articles to learn more –

  1. PowerShell String Functions
  2. PowerShell Commands
  3. PowerShell Operators
  4. How To Install PowerShell
  5. Array in PowerShell with Examples
  6. Type Casting in Python with Examples
Popular Course in this category
Programming Languages Training (41 Courses, 13+ Projects, 4 Quizzes)
  41 Online Courses |  13 Hands-on Projects |  322+ Hours |  Verifiable Certificate of Completion
4.5
Price

View Course

Related Courses

Shell Scripting Training (4 Courses, 1 Project)4.9
All in One Data Science Bundle (360+ Courses, 50+ projects)4.8
Data Visualization Training (15 Courses, 5+ Projects)4.7
0 Shares
Share
Tweet
Share
Primary Sidebar
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

ISO 10004:2018 & ISO 9001:2015 Certified

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

EDUCBA
Free Data Science Course

SPSS, Data visualization with Python, Matplotlib Library, Seaborn Package

*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 Login

Forgot Password?

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.

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.

Let’s Get Started

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

Loading . . .
Quiz
Question:

Answer:

Quiz Result
Total QuestionsCorrect AnswersWrong AnswersPercentage

Explore 1000+ varieties of Mock tests View more