C#,vb.net,MVC,Jquery,javascript,jscript,vbscript,html,vb,sharepoint,COM,WPF,WCF,Wwf,Asp,Asp.net,questions & answers,

Latest in Sports

Tuesday, October 14, 2014

Learning Windows PowerShell online with easy steps



Introduction

Windows PowerShell is Microsoft's task automation and configuration management framework, consisting of a command-line shell and associated scripting language built on .NET Framework. It enables administrators to perform administrative tasks on both local and remote Windows systems.

In PowerShell, administrative tasks are generally performed by cmdlets (pronounced command-lets), which are specialized .NET classes implementing a particular operation. Sets of cmdlets may be combined together in scripts.

Power shell command mode  intorduction
Power shell command mode
Important Keyboard Shortcuts
Power shell command mode  short cut keys
Power shell short cut keys




Along with the commands, a number of characters in the console have special meanings.
Piping: The vertical bar "|" symbol pipes the results of a command to the next.

Ex. Dir | Sort-Object Length | Select-Object Name, Length
Redirection: The symbol ">" redirects the results of a command to a file. You can then open and view the file contents. The symbol ">>" appends information to an existing file.
Ex. Help > help.txt
Ex. Help >> help.txt

Interactive Power Shell
PowerShell as a Calculator- You can use the PowerShell console to execute arithmetic

 operations the same way you would with a calculator.

  Ex.- 2+4, (12+5) * 3 / 4.5

Parentheses play a special role in PowerShell as they always works from the inside out: 

the results inside the parentheses are produced before evaluating the expressions outside

 of the parentheses, i.e. (2*2)*2 = 4*2.
Operators:-

Operator
Description
+
Adds two values
-
Subtracts two values
*
Multiplies two values
/
Divides two values
%
Supplies the rest of division




          Cmdlets: "Genuine" PowerShell Commands- PowerShells internal commands are called 'cmdlets'. The "mother" of all cmdlets is called Get-Command:
  syntax:- Get-Command -commandType cmdlet
          Cmdlet names always consist of an action (verb) and something that is acted on (noun). This naming convention helps you to find the right command. Let's take a look at how the system works.
        ex. Get-Command -verb get
        ex. Get-Command -noun service

The powerful command-  “Get-help”
           You can look up help for any cmdlet using Get-Help:
     ex. Get-Help Get-Command  –detailed
     ex. Get-Help Get-service  –full
     ex. Get-Help Get-service  –examples
          You can easily discover commands for certain actions because Get-Command also allows wildcards:
    ex. Get-Command *help* -CommandType cmdlet

          Using Named Parameters: Named parameters really work like key-value pairs. You specify the name of a parameter (which always starts with a hyphen), then a space, then the value you want to assign to the parameter.
          Let's say you'd like to list all files with the extension *.exe that are located somewhere in the folder c:\windows or in one of its subdirectories, you could use this command:
   
     ex. Get-ChildItem -path c:\windows -filter *.exe -recurse –name

Note- recurse is one of the most famous parameters meaning: repeat the procedure on sub-folders.
Aliases: Giving Commands Other Names:
          In every day admin life, you want short and familiar commands. This is why PowerShell has a built-in alias system as it comes with a lot of predefined aliases.
            Get-ChildItem c:\
            Dir c:\
            ls c:\
          You can also get the list of aliases using the cmdlet Get-Alias.
          Just use the PowerShell pipeline which feeds the result of a command into the next one and chains together commands.
 ex. Get-Alias | Where-Object {$_.Definition -eq "Get-ChildItem"}
          Anyone can create a new alias, which is a shortcut for another command. The cmdlet Set-Alias adds additional alias definitions.
   ex. Set-Alias edit notepad.exe
          You can simply delete it using Remove-Item:
   
   ex- Remove-item alias:edit

Variables


          Variables store information temporarily so you can take the information contained in a variable and process it in further steps.
Example1:
# Create variables and assign to values
$amount = 120
$VAT = 0.19
# Calculate:
$result = $amount * $VAT
# Output result
$result
22.8


Example2:
# Replace variables in text with values:
$text = "Net amount $amount matches gross amount $result"
$text
Net amount 120 matches gross amount 142.8
          PowerShell creates new variables automatically so there is no need to specifically "declare“ variables. Simply assign data to a variable. The only thing you need to know is that variable names are always prefixed with a "$".

Assigning and Returning Values:


The assignment operator "=" sets a variable to a specified value. You can assign almost anything to a variable, even complete command results:
Example:
# Temporarily store results of a cmdlet:
$listing = Get-ChildItem c:\
$listing

Populating Several Variables with Values Simultaneously:

You could set a whole series of variables to one shared initial value:
# Populate several variables with the same value in one step:
$a = $b = $c = 1
$a
$b
$c

Exchanging the Contents of Variables:
Traditional Programming-
In traditional programming languages, that would require several steps:
$Value1 = 10
$Value2 = 20
$Temp = $Value1
$Value1 = $Value2
$Value2 = $Temp

Simple steps with Power Shell-
With PowerShell, swapping variable content is much easier. First of all, you can write several statements in one line if you separate the statements from each other by semi-colon. Second, assignment operators will accept several variables on each side that replace each other:
# Exchange variable values:
$Value1 = 10; $Value2 = 20
$Value1, $Value2 = $Value2, $Value1

Overview of Variables in Use:
PowerShell keeps a record of all variable assignments, which is accessible via a virtual drive called variable:
To see all currently defined variables, you should just output this drive to a list:
Dir variable:
Finding Variables:
Dir variable:value*
Dir variable: -include value* -exclude *1*

Verify Whether a Variable Exists:

Similar to files, variables are stored in their own "drive" called variable:and every variable has a path name that you can verify with Test-Path:
Examples:
# Verify whether the variable $value2 exists:
Test-Path variable:\value2
True
# verify whether the variable $server exists:
Test-Path variable:\server
False

Deleting Variables:

Because variables are deleted automatically as soon as you exit PowerShell, you don't necessarily need to clean them up manually. If you'd like to delete a variable immediately, again, do exactly as you would in the file system:
Examples
# create a test variable:
$test = 1
# verify that the variable exists:
Dir variable:\te*
# delete variable:
del variable:\test
# variable is removed from the listing:
Dir variable:\te*

PowerShell Commands Return Arrays

If you store the result of a command in a variable and then output it, you might at first think that the variable contains plain text:
$a = ipconfig
$a

Storing Results in Arrays

This is how you identify arrays:
$a = "Hello"
$a -is [Array]
False
$a = ipconfig
          $a -is [Array]
True
If the result is an array, you can find the number of elements stored in it by using the Count property:
          $a.Count

Creating New Arrays:

You can create your own arrays, too. The easiest way is to use the comma operator:
$array = 1,2,3,4
$array
There's even a special shortcut for sequential numbers:
$array = 1..99
$array


Polymorphic Arrays:

Just like variables, individual elements of an array can store any type of value you assign. This way, you can store whatever you want in an array, even a mixture of different data types. You can separate the elements using commas:
Examples:
$array = "Hello", "World", 1, 2, (Get-Date)
$array
Note:-Parentheses identify a sub-expression and tell PowerShell to evaluate and process it first. So “Get-Date” cmdlet enclosed in a parentheses.

Addressing Array Elements:

Every element in an array is addressed using its index number. Negative index numbers count from last to first. You can also use expressions that calculate the index value:
Examples:
$array[0] $array = -5..12
# Access the first element:
$array[0]
# Access the last element
$array[-1], $array[$array.Count-1],

Choosing Several Elements from an Array:

You can use square brackets to select multiple elements in an array.
# Store directory listing in a variable:
$list = dir
# Output only the 2nd, 5th and 8th entry:
$list[1,4,7]

Adding Elements to an Array and Removing Them

You can simply use the "+=" operator to do that and then add new elements to an existing array but remove is littlie tricky.
$array += "New Value“
$array=$array|?{$_ -ne “Element to remove”}

PowerShell Pipeline


Pipeline(|) is used for passing the result of one step to next step for execution.
Example:
Dir | Sort-Object Length | Select-Object Name, Length |
ConvertTo-Html | Out-File report.htm
.\report.htm

Formatting Pipeline Results:

Transforming objects produced by the pipeline is carried out by formatting cmdlets. There are four choices:
Get-Command -verb format
Examples-
Dir | Format-Table Name, Length
Grouping Information
Group-Object works by grouping similar objects and then reporting their number.
Get-Service | Group-Object Status


Conditions


Formulating a Condition with Where-Object


The name of a process can be found in the Name property. If you're just looking for the processes of the Notepad, your condition should be name -eq 'notepad'. Now, supply this condition to Where-Object:
Get-Process | Where-Object { $_.name -eq 'notepad' }
Get-Process | Where-Object { $_.company -like 'micro*' } | Format-Table name, description, company
ForEach
The simplest and most useful loop is foreach. These loop performs an operation for each of input objects. For example:
$array = 1,2,3,4,5
$array | ForEach {Write-Host $_}
For
For loop is standard loop to execute a specific number of times
For ($i=1; $i -lt 5; $i++) {Write-Host $i}

While
The While statement performs an operation until the condition is true.
$i = 1
While($i -lt 5) {Write-Host $i; $i++}
While loop can be used in several different variants: do while and do until.
Do while
Do while is executes as long as condition is true but in first time is always execute.
$i = 1
do {Write-Host $i; $i++}
while ($i -lt 5)
Do Until
Do until works almost the same like do while but is executes until the condition is not true.
$i = 1
do {Write-Host $i; $i++}
until ($i -gt 5)




No comments:

Post a Comment