Tuesday, 20 January 2015

PowerShell Variables

Dealing with Variables in PowerShell.


Variables play a important role in any programming language and PowerShell is no exception for it.
Understanding Variables and playing with them is the key to essentially make your code more effective and helps us to present the code in more human readable format.

Here we would start with the basics of variable usage and declaration, calling and assigning stuff to them.

NOTE: I would keep this current line as note on all my other posts, which I would strongly recommend.Fire PowerShell Console and start typing along with me.

#Variables to store your stuff
#Assigning a variable


$FirstVar=33
${First Var}="PowerShell"

#To Get Output a variable from PS.

$MyVar
${My Var}
Write-Output $MyVar

#Strongly declare a  type of variable it would be.

#Here we tell the type of data we store in the respective variable.

[String]$MyName="VenuGopal"
 [int]$Number="123"

#Accepts only integer values below and we tried to add string and it would throw us error.
 [int]$Oops="Venu"


#Accepting value from console, storing and output the variable.
[string]$ComputerName=Read-host "Enter Computer Name"
Write-Output $ComputerName

#Assigning computer name to variable and calling that variable from a Commandlet.
$computerName="localhost"
Get-service -name bits -ComputerName "$ComputerName" |
    Select MachineName, Name, Status


Dealing with Quotes 

$ps="PowerShell"

# Mostly we use double quotes, it is used to display test along with variables that would be resolved later as per ther script together

"This is a variable $ps, and $ps is Fun!!"


#Single Quotes produce output as it is, the function, special stuff are simply ignored!

'This is a variable $ps, and $ps is Fun!!'

# the ` (the key on the tilt key above the tab would allow to ignore the next characters functionality if it had any.
#Typically the "/" "\" or some need where we have to nullify the force of some special character.. Soon you will get into this as we progress deeper :)


"This is a variable `$ps, and $ps is Fun!!"


#Output for the above three lines.

This is a variable PowerShell, and PowerShell is Fun!!
This is a variable $ps, and $ps is Fun!!
This is a variable $ps, and PowerShell is Fun!!

As said, we would gradually add more complex stuff as we progress.

No comments:

Post a Comment