EDUCBA

EDUCBA

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

PowerShell Variable in String

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

PowerShell Variable in String

 

Introduction to PowerShell Variable in String

Variables in a PowerShell is a way to store the values inside them, and using these variables in a string is a method to represent those variables by expanding it in a double quote and also representing variables in different ways like string formatting or direct PowerShell variable and performing operations for the variable inside the string when they store the cmdlet values and normal operation like the string concatenation.

Start Your Free Data Science Course

Hadoop, Data Science, Statistics & others

Syntax of PowerShell Variable in String

There are no specific methods for the variable in a string, but there are ways when the string is declared we can expand the variables inside.

For example, declaring string variables outside and using them inside the double quote, single quote, here-string, PowerShell string array, or representing them in the Invoke-Command.

Description:

PowerShell declares a variable by using the $ sign and the variable name.

For example, $Services. When we declare any type (Integer, double, string, DateTime) of the variable and when we use them inside the string variable, it automatically converts that variable to the string.

Code:

$num = 20
$num.GetType()

Here, we have declared the $num variable, and its value is 20, and its datatype is an integer, as shown in the below output.

Popular Course in this category
Sale
Shell Scripting Training (4 Courses, 1 Project)4 Online Courses | 1 Hands-on Project | 18+ Hours | Verifiable Certificate of Completion | Lifetime Access
4.5 (9,060 ratings)
Course Price

View Course

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

Output:

Powershell Variable in String 1

When we use this variable inside the string, let see what output it produces.

Code:

Write-Output "Representing $num to string"

Output:

Powershell Variable in String 2

Although the number is 20, it was represented inside a string, but its datatype is preserved unless it is explicitly converted to the string. Similarly, for the other data types, the string can convert any variable to the string.

Code:

$a = 10.2
Write-Output "Representing float $a to string"
$b = "Hello World"
Write-Output "Representing String $b to string"

Output:

Powershell Variable in String 3

Single-quote and Double-Quote in the PowerShell are the same, but expanding the variable makes a huge difference because single-quote string can’t expand the variable.

Code:

"Expanding Number: $num variable with the double-quote"

Output:

double-quote

Code:

'Expanding Number: $num variable with the single-quote'

Output:

single-quote

There are many other ways we can use the variable in a string.

Examples of PowerShell Variable in String

Given below are the examples of PowerShell Variable in String:

Example #1 – Displaying variable with the string formatting.

When there are variables to display in the string, we can display them using the string formatting method -f with ‘{}’.

We have the two variables in this example and how generally we display them.

Code:

$a = "Hello world"
$b = "Microsoft Azure"
Write-Output "First Variable: $a, Second Variable: $b"
"Without Write-Output, First Variable: $a, Second Variable: $b"

Output:

Powershell Variable in String 6

With the formatting method, we can display the variables as shown below.

Code:

"Formatting method: First Variable: {0}, Second Variable: {1}" -f $a, $b

Output:

Powershell Variable in String 7

Example #2 – Using the variable inside the Here-String.

When we expand the variables inside the Here-String @” ”@, the use of Single or Double quotes matters. When we use the single quote, it can’t get the value of the variable, but with the double-quote, it is possible.

Code:

$val1 = "Hello world"
$val2 = "Microsoft PowerShell"
@"
This is Here-String
First Variable: $val1
Second Variable: $val2
"@

Output:

Using the variable inside the Here-String

With single-quote.

Code:

@'
This is Here-String
First Variable: $val1
Second Variable: $val2
'@

Output:

With single-quote

Example #3 – Using the cmdlet output with a variable inside the string.

We can use the output of the variable inside the PowerShell string, and we can also expand their properties.

Code:

$ser = Get-Service -Name WinRm
$ser

Output:

variable inside the string

When we expand the service name.

Code:

Write-Output "Service Name is $ser.Name"

Output:

Powershell Variable in String 12

We could get the output of the service, but if you notice, it is the type of the service name, not the actual service name, so if you want the proper output, we need to use the $ variable before using the service variable.

Code:

Write-Output "Service Name is $($ser.Name)"

Output:

Powershell Variable in String 13

Or you can use the string formatting methods as shown below.

Code:

"Service name is : {0}" -f $ser.name

Output:

Powershell Variable in String 14

Let’s take another example of expanding the cmdlet output variable inside the here-string.

Code:

@"
Today's date is $(Get-Date)
Today's Day is $((Get-Date).DayOfWeek)
Today's Day of the year is $((Get-Date).DayOfYear)
"@

Output:

Powershell Variable in String 15

Example #4 – Using the variable inside the Invoke-Command string.

Using the Invoke-Command, when we use the variable inside the string and get the value that is out of the Invoke-Command scope, we can’t get its value.

Code:

$value = "2021"
Invoke-Command -ComputerName LabMachine2k16 -ScriptBlock {
Write-Output "The outside variable is: $value"
}

Output:

Invoke-Command

This is not the problem with the string or the variable, but the variable is outside of the scope. So for this method, we need to pass it using the -ArgumentList parameter.

Code:

$value = "2021"
Invoke-Command -ComputerName LabMachine2k16 -ScriptBlock {
param(
$value
)
Write-Output "The outside variable is : $value"
} -ArgumentList $value

Output:

Powershell Variable in String 17

Example #5 – Using the Variables in a string inside the hashtable.

We can also use the variables in a string inside the hashtable. In the below example, we can directly use the variable in the value field but just to show that the expansion of the variable supports in the string supported in the hashtable.

Code:

$Ser = Get-Service -Name WinRm
@{
ServiceName = "$($Ser.Name)"
Starttype = "$($ser.StartType)"
Status = "$($ser.Status)"
}

Output:

inside the hashtable

Example #6 – Representing the array in the PowerShell string.

We can use indexing to get the output of the array using the string.

Code:

$services = @("Winrm", "Spooler", "w32Time")
for($i=0; $i -lt $services.Count; $i++){
"Service Name : $($services[$i])"
}

Output:

Representing the array

We can also use the foreach method.

Conclusion

Variables in the PowerShell string are very useful when we store the output to the file when we want to minimize the efforts by expanding the variable of the cmdlet inside the string instead of using the additional variables for cmdlet expansion which makes them easy to display and format the values inside the string.

Recommended Articles

This is a guide to PowerShell Variable in String. Here we discuss the introduction to PowerShell Variable in String along with examples. You may also have a look at the following articles to learn more –

  1. PowerShell Sleep
  2. PowerShell SubString
  3. PowerShell not like
  4. Else If in PowerShell

All in One Data Science Bundle (360+ Courses, 50+ projects)

360+ Online Courses

50+ projects

1500+ Hours

Verifiable Certificates

Lifetime Access

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 Parameter
    • PowerShell Stop Service
    • 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 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

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.

EDUCBA Login

Forgot Password?

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.

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.

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

Special Offer - Shell Scripting Course Learn More