2. Agenda
2
• What is PowerShell
• PowerShell Architecture
• CmdLets
• Alias
• PowerShell Providers
• PowerShell Scripting Basics
• PowerShell Pipeline
3. What is Windows PowerShell ?
3
• Windows PowerShell™ is a task-based command-line shell.
• It’s a scripting language designed for IT Professional.
• Built on the .NET Framework.
• Windows PowerShell™ helps IT professionals to automate the
administration of the Windows operating system and
applications that run on Windows.
4. Why PowerShell ?
4
• It’s not going away any time soon ( Microsoft has made it clear that PowerShell is here to stay. That’s
why we have PowerShell version 2 included in Windows Server 2008 R2 and Windows 7 by default.)
• Most Microsoft products will eventually use it
• You can’t do everything from the GUI any more
• It can make your life easier( Example: If you need to update an Active Directory attribute for a thousand
users. Performing the task manually would likely take hours to complete. Using PowerShell, you can complete the task using
a single line of code.)
• Many GUIs are PowerShell front ends ( best known example of this is the Exchange Management
Console )
• You can use PowerShell commands to manage your domains
• It enables interactivity between products
5. How its differs ?
5
• PowerShell is object-based not text-based
Traditional command prompt output is text-based while output in PowerShell is not. It
looks like text but it is actually an object. With traditional scripting, if you wanted to
use the output of one command in another, additional programming would be
required to manipulate the data in a format the second command could understand
• PowerShell Commands are customizable
PowerShell commands are referred to as Cmdlets, PowerShell gives you the flexibility
to create your own CmdLets
• PowerShell is a Command line interpreter and a scripting environment
With PowerShell not only you can enter commands, you can build your own script-
blocks.
6. PowerShell Application
Windows PowerShell Console
• Similar to the Command Prompt
• Launching Windows PowerShell
Console.
Go to Start -> All Programs ->
Accessories -> windows PowerShell ->
Windows PowerShell
• You can also launch PowerShell
from a command prompt
start -> run by simply typing
PowerShell
Windows PowerShell ISE
• Writing PowerShell script *.PS1
and executing through
PowerShell console.
• Launching Windows PowerShell
Console.
Go to Start -> All Programs ->
Accessories -> windows PowerShell ->
Windows PowerShell ISE
• You can also launch PowerShell
from a command prompt
start -> run by simply typing
PowerShell ISE
6
7. PowerShell Architecture
7
The host is the
interface between the
commands and the
Windows PowerShell
engine
A host application is any application that loads the Windows PowerShell engine into its process and
uses it to perform operations.
A runspace is the operating
environment for the
commands invoked by the
host applicationThe pipeline is the
container for the
cmdlets and scripts
that are run
programmatically by
the host application
PowerShell Providers are .NET programs that
allow us to work with data stores. Some built in
providers are File System providers, Certificate
providers, etc.
Default - PowerShell.exe
Console Application
Windows Application
Web Application
8. PowerShell Console - Shortcut Keys
8
• Page Up – Jumps to the first command in the history buffer.
• Page Down – Jumps to the last command in the history buffer.
• Up Arrow – goes back one command in the history buffer.
• Down Arrow – goes forward one command in the history buffer.
• Home – Jumps to the beginning of the command line.
• End – Jumps to the end of the command line.
• Ctrl+LeftArrow – goes to the left one word at a time.
• Ctrl+RightArrow – goes to the right on word at a time.
• Tab – Completes input .
• F7 – Shows history buffer (use the up and down arrow keys to navigate the
buffer).
9. 9
Cmdlets are compiled code that are available to the PowerShell environment. PowerShell
commands have been standardized using a "verb-noun" naming convention. This standard
simplifies the learning curve and provides a better description of what the cmdlet does
To see a list of cmdlets available in PowerShell, type the following cmdlet:
Get-Command (Get is your verb and Command is your noun)
Get-Command –Verb Get: List all the commands which has verb “Get”.
Get-Command –Noun Service: List all the commands which has noun “Service”.
PowerShell CmdLets
10. 10
It is important to find information quickly and easily. Get-Help cmdlet has been designed for that
purpose. It displays help about Windows PowerShell cmdlets and concepts.
Get-Help: Information about cmdlets and concepts. Includes description, syntax, and remarks
Get-Help *: Information about all available help topics.
Get-Help Get-Service: Information about a specific cmdlet.
Get-Help Get-Service –Example: Information about a specific cmdlet with examples
CmdLets – Getting Help and Examples
11. 11
Get-Process: List all the process running in the machine
Get-Service: List all the service running in the machine
Get-Location: Gets the current path
Get-Process –name notepad Get-Service –name browser
Using CmdLets
Alias in CmdLets
An alias is an alternative name assigned to a cmdlet.
• Built-in Aliases – Predefined alternative names for Windows, Unix, and PowerShell cmdlets.
• User-defined Aliases – Custom alternative names created by the user.
Get-Alias: List all the alias exist in the powershell commands.
Creating Alias: New-Alias Hist Get-History.
Cmdlets to create new alias Customized Alias name Cmdlets for which you need to create alias
12. 12
Common Parameters: (Not all cmdlets use this parameters)
• -whatif – Cmdlet is not actually executed, provides information about “what would happen” if executed.
• -confirm - Prompt user before executing cmdlet.
• -Verbose - Provides more detail.
• -debug - Provides debugging information.
• -ErrorAction - Instructs cmdlet to perform an action when errors occur. Such as: continue, stop, silently continue, and
inquire.
• -ErrorVariable - Use a specific variable to hold error information. This is in addition to the standard $error variable.
• -OutVariable - Variable used to hold output information.
• -OutBuffer - Hold a certain number of objects before calling the next cmdlet in the pipeline.
Stop-Process –name notepad –whatIf
Stop-Process –name notepad -confirm
CmdLets – Parameters, Objects, and Formatting
13. 13
Objects:
Cmdlets are object by default. Get-Member helps to identify all the properties & methods exist in a cmdlets
Get-Service | Get-Member: List all the properties and methods of the Get-Service cmdlets
Get-Service | Get-Member -MemberType Method: List only the methods
Get-Service | Get-Member –MemberType Property: List only the property
14. 14
Formatting Output:
The “Format-” cmdlets allow us to choose which format to display results in.
• Format-List Displays the data in list
• Format-Table Displays the data in rows and column
• Format-Wide Compresses results of a list, to fit the screen
Get-ChildItem C:Windows | Format-Table: Displays the folders under C:Windows
Get-ChildItem C:Windows | Format-Table –AutoSize : (-AutoSize to assist us with white space issues.)
Formatting Output (html, csv):
Get-Process | ConvertTo-html: Convert the output to html, Display the result in PowerShell console.
Get-Process | ConvertTo-html | out-file “C:Processes.html”: Saves the output to a file.
Get-Process | Export-CSV Processes.csv: Convert the output to Process.csv file.
Invoke-Item Processes.csv: Open the exported Process.csv file.
15. 15
PowerShell Providers are .NET programs that allow us to work with data stores as if they were mounted
drives.Simplifies accessing external data outside the PowerShell environment. For example, we can access the
registry as if it were a file system.
Get-PSProvider: List providers available in PowerShell
To use any of the above listed providers , First we need to connect the providers by mounting PowerShell Drive.
Most Providers have only one PSDrive, the exceptions are the FileSystem Provider(depends on the number of
drives on the system) and the Registry Provider(HKLM and HKCU).
Get-PSDrive: List the available powershell drivers.
PowerShell Providers
16. 16
Using PowerShell Certificate Providers:
Set-Location cert:: Set Location to the Cert PSDrive .
Get-ChildItem: List all the Certificates on the System.
Get-ChildItem -Recurse | Export-CSV “D:Certificates.csv”: Export the certificate to a Certificates.csv file.
Invoke-Item “D:Certificates.csv”: Open the exported certificates.
17. 17
• Variables, Arrays, Xml and Hash tables.
• Arithmetic & Comparison, Logical Operators
• Using Conditional Logic.
• Processing data with Loops.
• Using Functions.
Variables:
Working on HashTable:
PowerShell Scripting Basic
S.No Type Description Example
1 [int] 32-bit signed integer [int]$x = 9
2 [long] 64-bit signed integer [long]$x = 98765432
3 [string] Fixed-length string of Unicode characters [string]$name = “Saravanan G”
4 [char] A Unicode 16-bit character [char]$a = ‘A’
5 [byte] An 8-bit unsigned character [byte]$a = 1
6 [bool] Boolean True/False value [bool]$a = 0
7 [decimal] An 128-bit decimal value [decimal]$i = 3.14
8 [single] Single-precision 32-bit floating point number [single]$s = 1
9 [double] Double-precision 64-bit floating point number [double]$d = 25.79
10 [xml] Xml object [xml]$x = get-content “D:Employee.xml”
11 [array] An array of values $comp = @(“Server1″, “Server2″, “Server3″)
12 [hashtable] Hashtable object $EmpName = @{“John” = 01; “Davis” = 02; “Smith” = 03}
Find Adding Remove Clear
$Employee[“John”] $Employee[“Mike”] = 04 $Employee.Remove("Mike") $Employee.Clear()
18. 18
Special Variables: Pre-defined within PowerShell
• $_ – Contains the current pipeline object, used in script blocks, filters, and the where statement.
• $Args – Contains an array of the parameters passed to a function.
• $Home – Specifies the user’s home directory.
• $PsHome – The directory where the Windows PowerShell is installed.
Get-Help about_automatic_variables: Cmdlet to view the complete list of special variables.
Operators:
Conditional Logic:
Arithmetic Comparison Logical
+ = Addition.
- = Subtraction
* = Multiplication
/ = Division
% = Modulus
-eq = Equal to
-lt = Less than
-gt = Greater than
-ge = Greater than or Eqaul to
-le = Less than or equal to
-ne = Not equal to
-not = Not
! = Not
-and = And
-or = Or
If Else Switch
$x = 2
if ($x -eq 5)
{Write-Host "Value is 5"}
elseif ($x -eq 4)
{Write-Host "Value is 4"}
else
{Write-Host "Value is 2"}
$objWMI = Get-WmiObject -Class win32_ComputerSystem -namespace
"rootCIMV2"
"Computer "+ $objWMI.name + " is a: "
switch ($objWMI.domainRole)
{
0 {Write-Host "Stand alone workstation"}
1 {Write-Host "Member workstation"}
2 {Write-Host "Stand alone server"}
3 {Write-Host "Member server"}
4 {Write-Host "Back-up domain controller"}
5 {Write-Host "Primary domain controller"}
default {Write-Host "The role cannot be determined"}
}
19. 19
Conditional Logic using loop:
PowerShell Function:
Function Time {Get-Date}
Function Add ($x, $y) #Passing Parameters in Function
{
$Ans = $x + $y
Write-Host “The Answer is $Ans”
}
do While While do Until For For Each
$i = 1
do {Write-Host $i;
$i++}
while ($i -le 5)
$i = 1
while ($i -le 5)
{Write-Host $i;
$i++}
$i = 1
do {Write-Host $i; $i++}
until ($i -gt 5)
$ints = @( 1, 2, 3, 4, 5)
for ($i=0; $i -le
$ints.Length – 1; $i++)
{Write-Host $ints[$i]}
$ints = @(1, 2, 3, 4, 5)
foreach ($i in $ints)
{Write-Host $i}
20. 20
Using $Args in Function:
Function Hello
{
“Hi $args, What are you doing ?”
}
Function Add
{
$args[0] + $args[1]
}
Using XML in PowerShell:
21. 21
Below is the Employee.PS1 file
In PowerShell, scripts will not run by default. PowerShell allows you to set a script execution policy. By calling the set-
executionpolicy passing and unrestricted value you can bypass this security block.
How to set Execution Policy:
set-executionpolicy -ExecutionPolicy Unrestricted
The Set-ExecutionPolicy cmdlet enables you to determine which Windows PowerShell scripts (if any) will be
allowed to run on your computer. Windows PowerShell has four different execution policies:
Restricted - No scripts can be run. Windows PowerShell can be used only in interactive mode.
AllSigned - Only scripts signed by a trusted publisher can be run.
RemoteSigned - Downloaded scripts must be signed by a trusted publisher before they can be run.
Unrestricted - No restrictions; all Windows PowerShell scripts can be run.
22. 22
How to Query cmdlets:
Get-Process | Where-Object {$_.handles -gt 500}
Get-Process | Where-Object {$_.handles -gt 500 -and $_.handles -lt 700}
Get-Process | Where-Object {$_.handles -gt 200 -and $_.name -eq "svchost"}
Get-Process | Where { $_.handles -gt 500 } | Sort handles | Format-Table
Get-ChildItem c:windows*.* | Sort-Object length -descending | Select-Object -last 3
Import-Csv D:Measure.txt | Measure-Object score -ave -max -min –sum
Import-Csv D:Measure.txt | Sort-Object score -ascending | Select-Object -first 5
Import-Csv D:Measure.txt | Sort-Object score | Select-Object -first 5
== --- Equal Content, => --- Value exist in right side, <= --- Value exist in left side
Display only the non equal
contents
Displays both equal and non equal
contents
Symbol | called as pipelines
$_ notation is used to represent the default
object (that is, the object being transferred
across the pipeline)
Import-CSV provides a way for you to read in
data from a comma-separated values file
23. Get-Process | Where { $_.handles -gt 500 } | Sort handles | Format-Table
23
Windows PowerShell Pipeline
26. Sample CmdLets
S.No Description Commands
1 Objects that use more than 10mb get-process | where-object { $_.ws -gt 10mb }
2 Reading a text file $a = get-content D:Power.txt
$a[0]
$a = get-content D:power.txt | measure-object -line -word –character
3 Event log get-eventlog -logname application -newest 10
4 All service running get-service | where {$_.status -eq 'running'}
5 Getting CmdLets examples get-help get-process -examples
6 Powershell version $PSVersionTable
($PSVersionTable).psversion
($PSVersionTable).buildversion
7 List all the variables dir variable:
8 Sorting Get-Process | Sort-Object ID –descending
9 Writing to a file Get-Process | Out-File D:ProcessList.txt
10 Colored text Write-Host "test" -foregroundcolor "green"
Write-Host "test" -backgroundcolor "red"
11 Converts To HTML Get-Service | ConvertTo-HTML -Property Name, Status > C:services.htm
12 WhatIf stop-process -name notepad -whatif
26
27. 27
References
Windows PowerShell Web site
PowerShell Features
TechNet Script Center Repository for PowerShell
PowerShell Tips
A-Z PowerShell 2.0 Commands
Windows PowerShell Cmdlet Help Topics
Windows PowerShell Quick reference
PowerShell Owner's Manual
PowerShell Tutorial
http://msdn.microsoft.com/en-us/library/ms714658.aspx
http://blogs.technet.com/b/heyscriptingguy/
http://en.wikipedia.org/wiki/Windows_PowerShell#Examples