Wednesday 29 June 2016

An Introduction to PowerShell – basics and how to define Variables

PowerShell is built into Windows, so there is no requirement of separate fee or licensing cost. In addition, different server products come with their own Power Shells, too, which expands the capability to do things you want using PowerShell.

For demo purpose I am using Windows PowerShell ISE.

PS-1

An introduction to scripts

Scripts in PowerShell are basically just text files with the special filename extension of ps1.

To create a script, you enter a series of PowerShell commands in a sequence in a new Notepad file or any text editor you like, and then save that file with extension as .ps1, where name of your file is a friendly description of your script with no spaces.

 

PS-2

How do I run my scripts?

To run a PowerShell script that you already have, you enter in a PowerShell window either:

The full path (folder and file name) of the script, like so: c:\powershell\myscript.ps1

Or

If your script is in the current directory the console is looking at, use a period and then a backslash, like this: .\myscrip.ps1

Other than this, there is nothing special needed for creating a script in PowerShell. You can simply add the commands you like.

 

PS-3

How do I define Variables?

In PowerShell, variables always have a dollar sign ($) prefixed before them.

Let us declare few variables right now:

$name = 'Ashwini'

$anynumber = 111074

$location = 'Ghaziabad'

$listofnumbers = 15,20,35,40

 

PS-4

If I want to define a variable with text as its value, I will require to add a single quote on either side of the text value.

Let’s say we want to find out the total number of cmdlets available on the system, we can use:

(get-command).count

 

PS-5

Let's declare a variable to store that count in. We’ll call it

$numbersofcmdlets

We will store output in this variable of the (get-command).count .

$numbersofcmdlets = (get-command).count

Now we can use this variable as part of something else.

For a simple example, let's look at the Write-Host cmdlet, which simply writes text to the screen of the machine hosting the PowerShell session. Write-Host has a lots of capabilities, but in its simplest form, you can just say:

Write-Host "Dynamics Nav Blog Site by Ashwini Tripathi"

You can integrate variables with Write-Host. You just call them with the dollar sign notation and work them right into your text.

For example, I can say:

Write-Host "There are $numbersofcmdlets commands available for use on this system."

 

PS-6

I will come up with more stuffs in my upcoming posts. 

Till then keep practicing and stay tuned for more details.

 

 

No comments:

Post a Comment