PowerShell Basics Part-1: Single Quotes (') and Double Quotes ("") in PowerShell.
Hi,
As i mentioned in the previous article that in the "PowerShell Basics" series we are going to cover the basics of PowerShell. Today we are covering variables. Variables plays an very important role in every scripting language and same in Powershell.
What are variables.?
Variables are just a container which can store anything {data} in it. We can Store "Strings", Integers, Doubles, or Output of the commands.
How to create a variables.?
It very simple, we can use New-Variable Cmdlet to create a new variable, Use -Name to named the variable and -Value to assign a value to it.
New-Variable -Name "Name" -Value "Aman"
We just created a new variable , but
How we can see or access variables ?
use dollar sign $ with variable name to access it.
$name
There is another and easy way for creating the variables.
Just provide the name which you want to use preceding with $ sign and then type = equal to {assignment operator} and after that value.
$name = "aman"
now try to access it using $name
Variables and Strings
Adding String in Variables
To add strings in variable make sure that the desired string is wrapped in single or double quotes.
If you don't wrap in quotes you will get the below error.
Integer and Variables
Saving integer in a variable is simple. Just assign the value to variable .
$var = 987
Storing Output of Cmdlets
we can store the output of Cmdlets in to the variables. You just need to specify the command which's output you want to store in a variable. I in below example i am saving the output of Get-Process in to variable $process.
$process = Get-Process
and when you see the variable $process and you can see that it contains the Output of Get-Process.
Assign a new value to variable.
use = equal to {equal assignment operator} to assign a new value. When you assigns a new value to variable the new value overwrites the old one.
In below example you can see that the old value of $name was "aman" but when we assigned a new value to $name we can see it overwrites the old one.
Adding Multiple lines in single variable
we can use += {Plus Equal Assignment operator} to add or assign multiple lines to the variables. This is quite handy when you write
$body = "This is a Email "
$body += " Generate from Server"
$body += " Which is located in India"
Remove variables
To remove variable we can use remove-Variable cmdlet and after that provide variable name .
remove-Variable body
let check if the variable exists. Nope nothing there.
Note: The value in variable are static and remain constant until you not changed them. For example you stored the value of Get-Process in a variable and after that you open notepad or any other app, the entry of new launched app wont be in the variable.
Thanks
Aman Dhally
you did greate a job, It is very easy to understand, keep looking further tutorial
ReplyDelete