SlideShare a Scribd company logo
1 of 29
Windows PowerShell
G. SARAVANAN
Duration : 60 Minutes
Agenda
2
• What is PowerShell
• PowerShell Architecture
• CmdLets
• Alias
• PowerShell Providers
• PowerShell Scripting Basics
• PowerShell Pipeline
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.
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
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.
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
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
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
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
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
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
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
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
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
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
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
• 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
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
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
Using $Args in Function:
Function Hello
{
“Hi $args, What are you doing ?”
}
Function Add
{
$args[0] + $args[1]
}
Using XML in PowerShell:
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
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
Get-Process | Where { $_.handles -gt 500 } | Sort handles | Format-Table
23
Windows PowerShell Pipeline
24
25
Comparison of cmdlets with similar commands
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
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
28
Questions ?
Thank you
G. SARAVANAN
saravanang@aditi.com | +91 9176665242

More Related Content

What's hot

Course 102: Lecture 20: Networking In Linux (Basic Concepts)
Course 102: Lecture 20: Networking In Linux (Basic Concepts) Course 102: Lecture 20: Networking In Linux (Basic Concepts)
Course 102: Lecture 20: Networking In Linux (Basic Concepts) Ahmed El-Arabawy
 
Introduction to Node.js
Introduction to Node.jsIntroduction to Node.js
Introduction to Node.jsVikash Singh
 
TypeScript Introduction
TypeScript IntroductionTypeScript Introduction
TypeScript IntroductionDmitry Sheiko
 
Introduction to PowerShell
Introduction to PowerShellIntroduction to PowerShell
Introduction to PowerShellBoulos Dib
 
Introduction to node.js
Introduction to node.jsIntroduction to node.js
Introduction to node.jsDinesh U
 
Basic command ppt
Basic command pptBasic command ppt
Basic command pptRohit Kumar
 
Lets make a better react form
Lets make a better react formLets make a better react form
Lets make a better react formYao Nien Chung
 
Course 102: Lecture 1: Course Overview
Course 102: Lecture 1: Course Overview Course 102: Lecture 1: Course Overview
Course 102: Lecture 1: Course Overview Ahmed El-Arabawy
 
Linux Basic Commands
Linux Basic CommandsLinux Basic Commands
Linux Basic CommandsHanan Nmr
 
Shell Scripting Tutorial | Edureka
Shell Scripting Tutorial | EdurekaShell Scripting Tutorial | Edureka
Shell Scripting Tutorial | EdurekaEdureka!
 
Course 102: Lecture 13: Regular Expressions
Course 102: Lecture 13: Regular Expressions Course 102: Lecture 13: Regular Expressions
Course 102: Lecture 13: Regular Expressions Ahmed El-Arabawy
 
Sending Email Basics PHP
Sending Email Basics PHPSending Email Basics PHP
Sending Email Basics PHPProdigyView
 
Linux command ppt
Linux command pptLinux command ppt
Linux command pptkalyanineve
 
Selenium - Introduction
Selenium - IntroductionSelenium - Introduction
Selenium - IntroductionAmr E. Mohamed
 

What's hot (20)

Course 102: Lecture 20: Networking In Linux (Basic Concepts)
Course 102: Lecture 20: Networking In Linux (Basic Concepts) Course 102: Lecture 20: Networking In Linux (Basic Concepts)
Course 102: Lecture 20: Networking In Linux (Basic Concepts)
 
Introduction to Node.js
Introduction to Node.jsIntroduction to Node.js
Introduction to Node.js
 
Shell programming
Shell programmingShell programming
Shell programming
 
TypeScript Introduction
TypeScript IntroductionTypeScript Introduction
TypeScript Introduction
 
Shell scripting
Shell scriptingShell scripting
Shell scripting
 
Introduction to PowerShell
Introduction to PowerShellIntroduction to PowerShell
Introduction to PowerShell
 
ASP.NET Web form
ASP.NET Web formASP.NET Web form
ASP.NET Web form
 
Typescript ppt
Typescript pptTypescript ppt
Typescript ppt
 
Php basics
Php basicsPhp basics
Php basics
 
Introduction to node.js
Introduction to node.jsIntroduction to node.js
Introduction to node.js
 
Filepermissions in linux
Filepermissions in linuxFilepermissions in linux
Filepermissions in linux
 
Basic command ppt
Basic command pptBasic command ppt
Basic command ppt
 
Lets make a better react form
Lets make a better react formLets make a better react form
Lets make a better react form
 
Course 102: Lecture 1: Course Overview
Course 102: Lecture 1: Course Overview Course 102: Lecture 1: Course Overview
Course 102: Lecture 1: Course Overview
 
Linux Basic Commands
Linux Basic CommandsLinux Basic Commands
Linux Basic Commands
 
Shell Scripting Tutorial | Edureka
Shell Scripting Tutorial | EdurekaShell Scripting Tutorial | Edureka
Shell Scripting Tutorial | Edureka
 
Course 102: Lecture 13: Regular Expressions
Course 102: Lecture 13: Regular Expressions Course 102: Lecture 13: Regular Expressions
Course 102: Lecture 13: Regular Expressions
 
Sending Email Basics PHP
Sending Email Basics PHPSending Email Basics PHP
Sending Email Basics PHP
 
Linux command ppt
Linux command pptLinux command ppt
Linux command ppt
 
Selenium - Introduction
Selenium - IntroductionSelenium - Introduction
Selenium - Introduction
 

Viewers also liked

Viewers also liked (11)

Ciencia y tecnología
Ciencia y tecnologíaCiencia y tecnología
Ciencia y tecnología
 
Геополітика 2(15)
Геополітика 2(15)Геополітика 2(15)
Геополітика 2(15)
 
Module 09 demos and retrospectives gla
Module 09   demos and retrospectives glaModule 09   demos and retrospectives gla
Module 09 demos and retrospectives gla
 
La Disgrafía
La DisgrafíaLa Disgrafía
La Disgrafía
 
Deck 11
Deck 11Deck 11
Deck 11
 
Eurostar innovation week 2 (3) (1)
Eurostar innovation week 2 (3) (1)Eurostar innovation week 2 (3) (1)
Eurostar innovation week 2 (3) (1)
 
Cell project 1 : Cell studying
Cell project 1 : Cell studyingCell project 1 : Cell studying
Cell project 1 : Cell studying
 
As tartarugas
As tartarugasAs tartarugas
As tartarugas
 
Cómo construir un banco de baterías de autos para apagones
Cómo construir un banco de baterías de autos para apagonesCómo construir un banco de baterías de autos para apagones
Cómo construir un banco de baterías de autos para apagones
 
Proceso de fabricacion del papel
Proceso de fabricacion del papelProceso de fabricacion del papel
Proceso de fabricacion del papel
 
El desarrollo evolutivo
El desarrollo evolutivoEl desarrollo evolutivo
El desarrollo evolutivo
 

Similar to PowerShell-1

Learn Powershell Scripting Tutorial Full Course 1dollarcart.com.pdf
Learn Powershell Scripting Tutorial Full Course 1dollarcart.com.pdfLearn Powershell Scripting Tutorial Full Course 1dollarcart.com.pdf
Learn Powershell Scripting Tutorial Full Course 1dollarcart.com.pdfClapperboardCinemaPV
 
CCI2019 - I've got the Power! I've got the Shell!
CCI2019 - I've got the Power! I've got the Shell!CCI2019 - I've got the Power! I've got the Shell!
CCI2019 - I've got the Power! I've got the Shell!walk2talk srl
 
PowerShell for SharePoint Admins
PowerShell for SharePoint AdminsPowerShell for SharePoint Admins
PowerShell for SharePoint AdminsRick Taylor
 
Windows power shell basics
Windows power shell basicsWindows power shell basics
Windows power shell basicsDan Morrill
 
PowerShell Workshop Series: Session 2
PowerShell Workshop Series: Session 2PowerShell Workshop Series: Session 2
PowerShell Workshop Series: Session 2Bryan Cafferky
 
Power shell training
Power shell trainingPower shell training
Power shell trainingDavid Brabant
 
Windows PowerShell - Billings .NET User Group - August 2009
Windows PowerShell - Billings .NET User Group - August 2009Windows PowerShell - Billings .NET User Group - August 2009
Windows PowerShell - Billings .NET User Group - August 2009John Clayton
 
Power shell for sp admins
Power shell for sp adminsPower shell for sp admins
Power shell for sp adminsRick Taylor
 
PowerShell for Penetration Testers
PowerShell for Penetration TestersPowerShell for Penetration Testers
PowerShell for Penetration TestersNikhil Mittal
 
PowerShellForDBDevelopers
PowerShellForDBDevelopersPowerShellForDBDevelopers
PowerShellForDBDevelopersBryan Cafferky
 
C++ Windows Forms L01 - Intro
C++ Windows Forms L01 - IntroC++ Windows Forms L01 - Intro
C++ Windows Forms L01 - IntroMohammad Shaker
 
Powershell Seminar @ ITWorx CuttingEdge Club
Powershell Seminar @ ITWorx CuttingEdge ClubPowershell Seminar @ ITWorx CuttingEdge Club
Powershell Seminar @ ITWorx CuttingEdge ClubEssam Salah
 
Automating Active Directory mgmt in PowerShell
Automating Active Directory mgmt in PowerShellAutomating Active Directory mgmt in PowerShell
Automating Active Directory mgmt in PowerShellConcentrated Technology
 
NIIT ISAS Q5 Report - Windows PowerShell
NIIT ISAS Q5 Report - Windows PowerShellNIIT ISAS Q5 Report - Windows PowerShell
NIIT ISAS Q5 Report - Windows PowerShellPhan Hien
 
Sql Server & PowerShell
Sql Server & PowerShellSql Server & PowerShell
Sql Server & PowerShellAaron Shilo
 
Holy PowerShell, BATman! - dogfood edition
Holy PowerShell, BATman! - dogfood editionHoly PowerShell, BATman! - dogfood edition
Holy PowerShell, BATman! - dogfood editionDave Diehl
 
PowerShell for SharePoint Developers
PowerShell for SharePoint DevelopersPowerShell for SharePoint Developers
PowerShell for SharePoint DevelopersBoulos Dib
 

Similar to PowerShell-1 (20)

Learn Powershell Scripting Tutorial Full Course 1dollarcart.com.pdf
Learn Powershell Scripting Tutorial Full Course 1dollarcart.com.pdfLearn Powershell Scripting Tutorial Full Course 1dollarcart.com.pdf
Learn Powershell Scripting Tutorial Full Course 1dollarcart.com.pdf
 
CCI2019 - I've got the Power! I've got the Shell!
CCI2019 - I've got the Power! I've got the Shell!CCI2019 - I've got the Power! I've got the Shell!
CCI2019 - I've got the Power! I've got the Shell!
 
PowerShell for SharePoint Admins
PowerShell for SharePoint AdminsPowerShell for SharePoint Admins
PowerShell for SharePoint Admins
 
Windows power shell basics
Windows power shell basicsWindows power shell basics
Windows power shell basics
 
PowerShell Workshop Series: Session 2
PowerShell Workshop Series: Session 2PowerShell Workshop Series: Session 2
PowerShell Workshop Series: Session 2
 
Power shell training
Power shell trainingPower shell training
Power shell training
 
Windows PowerShell.pptx
Windows PowerShell.pptxWindows PowerShell.pptx
Windows PowerShell.pptx
 
No-script PowerShell v2
No-script PowerShell v2No-script PowerShell v2
No-script PowerShell v2
 
Windows PowerShell - Billings .NET User Group - August 2009
Windows PowerShell - Billings .NET User Group - August 2009Windows PowerShell - Billings .NET User Group - August 2009
Windows PowerShell - Billings .NET User Group - August 2009
 
Power shell for sp admins
Power shell for sp adminsPower shell for sp admins
Power shell for sp admins
 
PowerShell for Penetration Testers
PowerShell for Penetration TestersPowerShell for Penetration Testers
PowerShell for Penetration Testers
 
PowerShellForDBDevelopers
PowerShellForDBDevelopersPowerShellForDBDevelopers
PowerShellForDBDevelopers
 
Windows PowerShell
Windows PowerShellWindows PowerShell
Windows PowerShell
 
C++ Windows Forms L01 - Intro
C++ Windows Forms L01 - IntroC++ Windows Forms L01 - Intro
C++ Windows Forms L01 - Intro
 
Powershell Seminar @ ITWorx CuttingEdge Club
Powershell Seminar @ ITWorx CuttingEdge ClubPowershell Seminar @ ITWorx CuttingEdge Club
Powershell Seminar @ ITWorx CuttingEdge Club
 
Automating Active Directory mgmt in PowerShell
Automating Active Directory mgmt in PowerShellAutomating Active Directory mgmt in PowerShell
Automating Active Directory mgmt in PowerShell
 
NIIT ISAS Q5 Report - Windows PowerShell
NIIT ISAS Q5 Report - Windows PowerShellNIIT ISAS Q5 Report - Windows PowerShell
NIIT ISAS Q5 Report - Windows PowerShell
 
Sql Server & PowerShell
Sql Server & PowerShellSql Server & PowerShell
Sql Server & PowerShell
 
Holy PowerShell, BATman! - dogfood edition
Holy PowerShell, BATman! - dogfood editionHoly PowerShell, BATman! - dogfood edition
Holy PowerShell, BATman! - dogfood edition
 
PowerShell for SharePoint Developers
PowerShell for SharePoint DevelopersPowerShell for SharePoint Developers
PowerShell for SharePoint Developers
 

More from Saravanan G

More from Saravanan G (7)

Wcat
WcatWcat
Wcat
 
ServiceFabric-Arch
ServiceFabric-ArchServiceFabric-Arch
ServiceFabric-Arch
 
Windows Azure Marketplace
Windows Azure MarketplaceWindows Azure Marketplace
Windows Azure Marketplace
 
PowerShell-2
PowerShell-2PowerShell-2
PowerShell-2
 
WindowsAzureIAAS
WindowsAzureIAASWindowsAzureIAAS
WindowsAzureIAAS
 
WindowsAzureSDK1.7
WindowsAzureSDK1.7WindowsAzureSDK1.7
WindowsAzureSDK1.7
 
AzureDocumentDB
AzureDocumentDBAzureDocumentDB
AzureDocumentDB
 

PowerShell-1

  • 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
  • 24. 24
  • 25. 25 Comparison of cmdlets with similar commands
  • 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