Vous êtes sur la page 1sur 84

POWERSHELL

- Rajkumar - Nikhil Sureka

Contents
Introduction to Windows PowerShell
Introduction to Windows PowerShell Installing Windows PowerShell in Windows Server 2008 Lab1 - Implementing Windows PowerShell

Overview of Windows PowerShell


Overview of Objects Working with Cmdlets Tab Expansion, Aliases, and History Using Variables and Types Lab2 - Lab: Working with Windows PowerShell Cmdlets, Aliases, Objects and Variables

Windows PowerShell is a command-line shell and scripting language designed especially for system administration. Built on the Microsoft .NET Framework, Windows PowerShell helps IT professionals control and automate the administration of Windows operating systems and applications that run on Windows.

History of Powershell
Windows Powershell is a Microsoft command-line shell and scripting language. It was first introduced in 2003. Its initial codename was MONAD which stood for Microsoft shell (MSH)

History of Powershell
The first official release was in 2006 which is when the name was changed from MONAD to Powershell.

v1.0 runs on Windows XP and Vista v2.0 runs on Windows 7 (and comes preinstalled)
It is available for both 32 bit and 64 bit platforms.

Introduction to Windows PowerShell


Download http://support.microsoft.com/kb/968929

Windows Management Framework (Windows PowerShell 2.0, Windows Remote Management (WinRM) 2.00, and Background Intelligent Transfer Service (BITS) 4.0)

Download PowerShell from Microsoft's site


http://www.microsoft.com/windowsserver2003/technologies/man agement/powershell/download.mspx

Download .NET Framework


PowerShell is an object based scripting language; consequently, it needs .NET Framework for the definitions of the Windows objects. PowerShell works fine with either .NET Framework v 2.0, or v 3.0. Search Microsofts site for:

Windows Scripting Languages


Presently, Microsoft Windows programmers have several options when it comes to scripting. They can use:
1. 2. 3. MS-DOS (or CMD) to create simple batch files VBScript for more complex programming PowerShell to make the most of the .NET framework

With one of the above or a combination of all, a programmer gets complete control of all of the objects on a Windows computer.

Windows Powershell Cmdlets


A cmdlet is a lightweight command that is used in the Windows PowerShell environment. Cmdlets follow a verb-noun naming pattern. Examples of verbs: get, set, new
Examples of nouns: service, item, date

Overview of Windows PowerShell



Windows PowerShell 2.0 is included with Windows 7 and supports existing scripts and command-line tools. Cmdlets are available for performing common system and administration tasks. The .NET framework is leveraged and provides access to thousands of objects. An extensible interface enables enterprise developers to build custom tools and utilities to administer their software.

Windows PowerShell 2.0 accepts and returns .NET objects which can be directly manipulated or sent to other tools or databases.

Exchange 2003 (VBScript)


Mailbox Statistics
Set listExchange_Mailboxs = GetObject("winmgmts:{impersonationLevel=impersonate}!\\COMPUTERNAME\ROOT\MicrosoftExchangeV2").InstancesOf(" Exchange_Mailbox") For Each objExchange_Mailbox in listExchange_Mailboxs WScript.echo "AssocContentCount = + objExchange_Mailbox.AssocContentCount WScript.echo " DateDiscoveredAbsentInDS = + objExchange_Mailbox.DateDiscoveredAbsentInDS WScript.echo " DeletedMessageSizeExtended = + objExchange_Mailbox. DeletedMessageSizeExtended WScript.echo " LastLoggedOnUserAccount = + objExchange_Mailbox. LastLoggedOnUserAccount WScript.echo " LastLogoffTime = + objExchange_Mailbox. LastLogoffTime WScript.echo " LastLogonTime = + objExchange_Mailbox. LastLogonTime WScript.echo " LegacyDN = + objExchange_Mailbox. LegacyDN WScript.echo " MailboxDisplayName = + objExchange_Mailbox. MailboxDisplayName WScript.echo " MailboxGUID = + objExchange_Mailbox. MailboxGUID WScript.echo " ServerName = + objExchange_Mailbox. ServerName WScript.echo " Size = + objExchange_Mailbox. Size WScript.echo " StorageGroupName = + objExchange_Mailbox. StorageGroupName WScript.echo " StorageLimitInfo = + objExchange_Mailbox. StorageLimitInfo WScript.echo " StoreName = + objExchange_Mailbox. StoreName WScript.echo " TotalItems = + objExchange_Mailbox. TotalItems Next

E12 (Monad Script) get-mailboxstatistics server $servername

Database Mgmt

Dim StorGroup as New CDOEXM.StorageGroup StorGroup.DataSource.Open "LDAP://" + DCServer + "/ CN=First Storage Group,CN=InformationStore,CN=" + Server + ",CN=Servers,CN=First Administrative Group, CN=Administrative Groups,CN=First Organization, CN=Microsoft Exchange,CN=Services, CN=Configuration," + DomainName StorGroup.MoveLogFiles("C:\newlogPath", 0)

move-storagegrouppath -identity First Storage Group log "C:\newlogPath

Recipient Mgmt

Dim objMailbox As CDOEXM.IMailboxStore


Set objMailbox = GetObject("LDAP://" + DCServer + "CN=FOO,CN=users," + DomainName) objMailbox.CreateMailbox "LDAP://" + DCServer + "/CN=Private MDB,CN=First Storage Group,CN=InformationStore,CN=" + Server + ",CN=Servers,CN=First Administrative Group, CN=Administrative Groups,CN=First Organization, CN=Microsoft Exchange,CN=Services, CN=Configuration,"

enable-mailbox -identity domain\FOO database First Storage Group\Private MDB

Overview of the Windows PowerShell 2.0 Integrated Scripting Environment (ISE)


The ISE enables you to run commands and design, write, test, and debug scripts in a Windows GUI

Command pane

Multiple tabs, each with its own command, output, and script pane

Output pane

Script pane

Using the Windows PowerShell ISE Editor


You can run any Windows PowerShell expression or command in Windows PowerShell ISE
Start the Windows PowerShell ISE:

From the Start menu, point to All Programs, point to Windows PowerShell 2.0, and then click Windows PowerShell ISE. In the Windows PowerShell console, type Cmd.exe, or in the Run box, type powershell_ise.exe.

Customize the Windows PowerShell ISE by:

Moving and resizing the Command pane, Output pane, and Script pane Showing or hiding the Script pane Changing the text size in all panes of Windows PowerShell ISE

Windows PowerShell ISE Profile


ISE has its own Windows PowerShell profile, Microsoft.PowerShell_ISE_profile.ps1 You can store functions, aliases, variables, and commands that you use in Windows PowerShell ISE in this profile

WinRM - Windows PowerShell Remoting features of Windows PowerShell are built on Windows Remote Remoting Management (WinRM)
Run an individual command, or create a persistent connection or session to run a series of commands

Remote administration is also known as remoting

Two types of remoting:


Fan-out remoting: provides one-to-many remoting to run scripts across multiple computers from a single console One-to-one interactive remoting: provides the ability to remotely troubleshoot a specific computer

Connecting to a Remote Computer


Two ways to create a connection to a remote computer:

Create a temporary connection


You can start an interactive session by using the Invoke-Command cmdlet with the ComputerName parameter. A temporary connection is created for the command and closes the connection when the command completes.

Create a persistent connection


Open a new Windows PowerShell session (PSSession) on the remote computer, then connect to the computer and enter the session.
The New-PSSession cmdlet creates the PSSession. The Enter-PSSession cmdlet connects you to the PSSession.

You can run as many commands as desired during the session. You must manually close the PSSession by using the Exit-PSSession cmdlet.

How Remote Commands Are Processed


1. Local computer sends the Windows PowerShell command to the remote computer using the WinRM protocol

2. Command runs in Windows PowerShell on the remote computer

3. Command results are sent back using the WinRM protocol and appear in Windows PowerShell on the local computer

All of the local input to a remote command is collected before any of it is sent to the
remote computer.

The output is returned to the local computer as it is generated.

Running Remote Commands


To run commands in a PSSession:
Use the Session parameter of the Invoke-Command cmdlet to specify the session Use the ComputerName parameter to retrieve objects from remote computers

To run a remote command on multiple computers:


Use the Invoke-Command for temporary connections and multiple computer names Use the Session parameter for persistent connections and multiple PSSessions Type the name of each computer in the ComputerName parameter of the InvokeCommand

To run a local script on remote computers


Use the FilePath parameter of the Invoke-Command cmdlet

Discovering PowerShell
PowerShell provides a discoverable environment. If you dont know something or do not remember browse around:
Get-Help (help) Get-Command (gcm) Get-PSDrive (gdr) Get-Member (gm)

Most of the commands support wildcards


PS C:\> get-command *snapin*

PowerShell Aliases
An alias is an alternative name assigned to a Cmdlet. Aliases allow users to quickly interact with the shell. The Cmdlet get-alias is used to list all built-in aliases as shown in the diagram on the next slide:

Powershell Providers
They are .NET programs used to provide easy access to information external to the shell environment in order for the users to view it and manage it.

To obtain a listing of all the providers, the GetPSProvider cmdlet is used. To work with specific providers, use the setlocation cmdlet then specify the provider drive.

Powershell Providers
There are seven types of providers namely:

1. Alias - Provides access to the windows PowerShell aliases and their values
Get-PSProvider Sl Alias:\ GCI | where-object {$_.name like s*}

2. Environment - Provides access to the Windows environment


variables.

3. FileSystem - Provides access to files and directories. 4. Function - Provides access to the functions defined in Windows PowerShell.

Powershell Providers cont.


5. Registry Provides access to the system registry keys and values. 6. Variable Provides access to Windows PowerShell variables and their values. 7. Certificate Provides read-only access to certificate stores and certificates.

Variables
Your Own Variables "Automatic- PowerShell Variables Environment Variables Drive Variables Scope of Variables Variable Types and "Strongly Typing" Variable Management: Behind the Scenes

Variable Name
You can use virtually any variable name you choose, names are not case sensitive. But, there are illegal characters such as; ! @ # % & , . and spaces. PowerShell will throw an error if you use an illegal character.

Variable Type
Powershell variable type is base on .NET Framework. Common variable is as below:
[adsi], [array], [bool], [byte], [char] [datetime], [decimal], [double] [int] or [int32], [long] [single], [scriptblock], [string] [WMI], [WMIclass], [xml]

Your Own Variables


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 "$ # Create variables and assign to values $amount = 120 $VAT = 0.19 # Calculate: $result = $amount * $VAT # Output result $result 22.8 # Replace variables in text with values: $text = "Net amount $amount matches gross amount $result" $text Net amount 120 matches gross amount 142.8

Exchanging the Contents of Variables


$Value1 = 10 $Value2 = 20 $Temp = $Value1 $Value1 = $Value2 $Value2 = $Temp $Value1 = 10; $Value2 = 20 $Value1, $Value2 = $Value2, $Value1

PowerShell keeps a record of all variable assignments, which is accessible via a virtual drive called variable:
Dir variable:value* Name ---value2 value1 Value ----20 10

Verify Whether a Variable Exists


Test-Path variable:\value2 True

$listing = Get-ChildItem c:\ $listing


Directory: Microsoft.PowerShell.Core\FileSystem::C:\ Mode LastWriteTime Length Name ---- ------------- ------ ---d---- 06.26.2007 15:36 2420 d---- 05.04.2007 21:06 ATI d---- 08.28.2006 18:22 Documents and settings d---- 08.08.2007 21:46 EFSTMPWP d---- 04.28.2007 02:18 perflogs (...)

# Populate several variables with the same value in one step: $a = $b = $c = 1

Cmdlets for Variable

Write-Protecting Variables: Creating Constants


New-Variable test -value 100 -description ` "test variable with write-protection" -option ReadOnly $test 100
$test = 200

The variable "test" cannot be overwritten since it is a constant or read-only. At line:1 char:6 + $test <<<< = 200 del variable:\test -force

Constant Variable
If you need strong protection like in traditional constants, you should create a variable with the Constant option. This will change the variable to a proper constant that may neither be modified nor deleted. Only when you quit PowerShell are constants removed. Variables with the Constant option may only be created with New-Variable.

New-Variable test -value 100 -description ` "test variable with copy protection" -option Constant New-Variable : A variable named "test" already exists. At line:1 Char:13 + New-Variable <<<< test -value 100 -description "test variable with copy protection" -option Constant

Automatic Variables.
PowerShell uses variables, too, for internal purposes and calls those "automatic variables. To understand the meaning of automatic variables, you can simply view their description:
Dir variable: | Sort-Object Name | Format-Table Name, Description autosize wrap Name ---$ ? ^ _ Description ----------Execution status of last command.

Environment Variables
Reading Particular Environment Variables
$env:windir C:\Windows Searching for Environment Variables Dir env:

Deleting and Modifying Environment Variables


del env:\windir $env:OS = "Apple MacIntosh OS X" Dir env:

# The folder is now added to the path environment: $env:path += ";C:\myTools"

Scope of Variables

All Variables are Object


[int]$Age=22 $Age.GetType() $Age GetType().Name $Age | Get-Member $Title=manager $Title.length $Title.CompareTo()

PSDrive

PSDrive Operation
Get-PSDrive mount -Name Seting -psProvider FileSystem Root "C:\Documents and Settings mount -Name MS -PSProvider Registry -Root HKLM\Software\Microsoft rdr -Name MS Set-Location Get-Location

Powershell Operator
Arithmetic Binary Operators
+, -, *, \, %, ++, --

Assignment Operators
=, +=, -=, *=, /=, %=

Logical Operators
!, -not, -and, -or

String Operators
+, *, -f, -replace, -match, -like

Comparison Operators
-eq, -ne, -gt, ge, -lt, le

Arithmetic Binary Operators


123+789 ; 222-876 34.5*44.2 ; 13/7 123%5 $var++ ; ++$var $var = $var + 1 $var-- ; --$var $var = $var 1

Assignment Operators
$var=3 $var+=3 ; $var-=3 $var*=3 ;$var/=3 ; $var%=3 $var = 0x10 echo $var 16 $var = 7.56e3 echo $var 7560 $var=7MB echo $var 7340043 (bytes)

Logical Operators
(7 -eq 7) -and (2 -eq 5) (7 -eq 7) -or (2 -eq 5) (9 -eq 9) -xor (4 -eq 4) ; (9 -eq 9) -xor (4 -eq 7) (3 -eq 3) -and !(2 -eq 2) (3 -eq 3) -and -not (2 -eq 9)

String Operators
-like ; -clike ; -ilike To be like as -notlike ; -cnotlike ;-inotlike To not be like as

-match ; -cmatch ;-imatch

Match

-notmatch ; -cnotmatch ; -inotmatch Not match

-contains ; -ccontains ; -icontains

Include

-notcontains; -cnotcontains ; -inotcontains

Not include

Comparison Operators
-le ; -cle ; -ile <= -eq; -ceq; -ieq = -ne; -cne; -ine != -gt; -cgt; -igt > -ge; -cge; -ige >= -lt; -clt; -ilt < -le; -cle; ile <=

Loop and Flow Control


If. elseif else Switch default ForEachForeach-Object For While Do.. While Do..Until Break & Continue

If. elseif else


If (< statement 1>) { < code 1> } Elseif (< statement 2>) { < code 2> } Else { <code n> }

Switch default
Switch [-regex|-wildcard|-exact][-casesensitive] -file <filename> (< variable >) { < Pattern 1> { code 1 } < Pattern 2> { code 2 } < Pattern 3> { code 3 } Default { code n } }

ForEachForeach-Object
ForEach ($<item or object> in $<Collection object>) { <code> } dir | ForEach -process { $_.length / 1024}

For
For (<initial>; < statement >; < count>) { <code> }

Foreach Loop
1) foreach ($number in 1,2,3,4,5,6,7,8,9,10,11,12 ) { $number * 7} 2) foreach ($number in 1... 12) {$number * 7}

3)$NumArray = (1,2,3,4,5,6,7,8,9,10,11,12)
foreach ($number in $numArray ) { $number * 7} 4) $NumArray = (1.. 12) foreach ($number in $numArray ) { $number * 7}

While, do while, do until


While (< statement >) { <code> } Do { < code > } While (< statement >) Do {<code> } Until (<statement>) ps. Until can wait something happen!!

While, Do While, Do Until


While Loops
- $i =7; while ($i -le 85) { $i; $i +=7 }

Do While Loop
- $i = 7; do {$i; $i +=7} while ($i -le 85)

Do Until
- $i = 7; do {$i; $i +=7} until ($i -gt 85)

Break; Continue
For ($i = 1; $i -le 10; $i++) { Write-Host $i If ($i -eq 5) { Write-Host "BREAK!! Break } } ForEach ($i in 1..10) { If ($i % 2) { Continue } $i }

Cmdlets
PSSnapin (subclass)
Default registers all Cmdlets CustomPSSnapin register specific Cmdlets

Parameters and Parameter Sets


Begin/End/StopProcessing ProcessRecord WriteObject

and WriteError

Cmdlets
The majority of the PowerShell functionality comes from Cmdlets Always in Verb-Noun format and never plural (Get-WmiObject or Get-Process) Cmdlets return objects not text Retrieve list of Cmdlets (Get-Command) Can tab complete

Sample Powershell Cmdlets


Below are sample Cmdlets following the verbnoun naming pattern:
PS C:\>get-childitem C:\
(Gets the items and child items in one or more specified locations.)

PS C:\>get-service
(Retrieve information about the services installed on your computer.)

PS C:\>set-location D:\
(It enables you to specify a new working location.)

PS C:\> set-location c:\my documents

5 key powershell commands


Get-Help(get-help set-* gives all cmdlets that start with Set-.) Get-Command (youll get back a list of all the Windows PowerShell
cmdlets)

Get-Member(will enumerate the properties and methods of that


object.)

Get-Psdrive (Gets the Windows PowerShell drives in the current


session)

Format-List(each property is displayed on a separate line)

Showing processes

Getting help on commands

Stopping a process(es)

Script Security Settings - Execution Policy


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.

Setting script execution policy


Use the Get-ExecutionPolicy cmdlet to retrieve the current effective script execution policy. Use the Set-ExecutionPolicy cmdlet to change the script execution policy to unrestricted as shown below:
Set-ExecutionPolicy unrestricted

Pipelining
One of the most powerful and possibly confusing aspects of PowerShell. The output of one program can be the input to another Pipelining is passing data and objects from one cmdlet to another in a very robust fashion.

A | B | C meaning the output of A goes to B, and the output of B goes to C.

Pipelining Example
PS C:\> Get-Process | where { $_.handlecount -gt 400 } | Format-List

This example is actually executing three cmdlets


1. The first, Get-Process, returns a list of all running processes

2. The second, Where {..} will return the conditioned value which handlecount is greater than 400.
3. Finally the Format-list will display the results in Alphabetic order

Pipelining Example Output


PS C:\> Get-Process | where { $_.handlecount -gt 400 } | Format-List

ProcessName Id : 1080 ProcessName Id : 1952 ProcessName Id : 2656 ProcessName Id : 1524

: csrss : explorer : Groove : inetinfo

Sorting
The sort-object cmdlet is used to produce a listing of items in ascending/descending order
Get-EventLog system -newest 5 | Sort-Object eventid

Produces the output below:

Running windows powershell scripts


Running a script can be done either within or outside PowerShell. Running the script within PowerShell requires the following steps:
1. Type the full path to the script 2. Include the name of the script 3. Ensure you include the PS1 extension
C:\mytest\RetrieveAndSortServiceState.PS1

Running windows powershell scripts


Running scripts outside PowerShell requires the following steps:
1. 2. 3. 4. 5. Type the full path to the script Include the name of the script Ensure you include the PS1 extension Feed this to the PowerShell.exe program Use the noexit argument to keep the PowerShell console after script execution

Powershell noexit C:\mytest\RetrieveAndSortServiceState.PS1

Utilities Object Manipulation


Command Action

Compare Group Measure Select Sort Tee Where

Compare 2 sets of objects Split a set of objects into groups Measure some property of a set of objects Select a set of properties from a set of objects Sort objects Make a copy of a set of objects Select a subset of objects

Utilities - Discovery
Command Function

Get-Help
Get-Command Get-Member Get-PSDrive

Help about PowerShell commands and topics Get information about anything that can be invoked Show what can be done with an object Shows what object stores are available

Transformation and Output


Commands Format -Custom -List -Table -Wide Out -File -Host -Printer -String Export/Import -CliXML -CSV ConvertTo -HTML Functions Convert objects into formatting records

Convert formatting records into output-specific directives.

Converts objects into and out of file formats

Converts object into other objects

Creating new items using Scripts


Files and Folders New-Item is a quick and easy way to create a new file or folder on your computer. Creating a file:
New-Item c:\scripts\new_file.txt -type file

Creating a folder: New-Item c:\scripts\Windows PowerShell -type directory

Creating multiple folders


$intFolders = 10 $intPad $i = 1 New-Variable -Name strPrefix -Value "testFolder" -Option constant do { if ($i -lt 10) {$intPad=0 new-item -path c:\mytest -name $strPrefix$intPad$i -type directory} else {new-item -path c:\mytest -name $strPrefix$i -type directory} $i++ }until ($i -eq $intFolders+1)

Deleting multiple folders


$intFolders = 10 $intPad $i = 1 New-Variable -Name strPrefix -Value "testFolder" Option constant do { if ($i -lt 10) {$intPad=0 Remove-item -path c:\mytest\$strPrefix$intPad$i} else {Remove-item -path c:\mytest\$strPrefix$i} $i++ }until ($i -eq $intFolders+1)

Access existing instrumentation


Bind to COM objects
$fso = New-Object -ComObject Scripting.FileSystemObject $m = [System.Runtime.InteropServices.Marshal] $word = $m::GetActiveObject("Word.Application")

Invoke methods/access properties


$fso.GetDrive(C:) $fso.VolumeName = System Drive

Understand/extend instrumentation
Extend and discover properties/methods
Update-TypeData Office.Word.Types.ps1xml $fso | Get-Member

Manipulate and format results


Define and import custom formating
Update-FormatData Office.Word.Format.ps1xml $word.RecentFiles | Sort name | Format-Table

Allows more simpler/more powerful COM scripts because of utilities and formatting

Windows Management Instrumentation (WMI) Model


It is a hierarchical namespace, in which the layers build on one another like a Lightweight Directory Access Protocol (LDAP) directory used in Active Directory, or the file system structure on a hard disk drive. WMI can be used to: report on drive configuration, report on available memory both physical and virtual, back up the event log, modify registry, schedule tasks, share folders, switch from a static to a dynamic IP address. The WMI model has three sections namely:
1. 2. 3. Resources Infrastructure Consumers

PowerShell provides native WMI support Get-WmiObject


Allows for inspection of WMI namespace Get-WmiObject list [-Namespace xx] Get-WmiObject Class xx Namespace xx Property xxx Filter xxx ComputerName xxx Credential xxx

Native language support


*WMI+ \\JPSDESK10\root\cimv2:Win32_Process.Handle="0 [WMICLASS] "ROOT\cimv2:WIN32_PROCESS" [WMISEARCHER]"select * from Win32_process WHERE Name = 'calc.exe'"

PowerShell provides native access to any .NET class Create any object
[reflection.assembly]::LoadWithPartialName("Syste m.Windows.Forms") $d = New-Object System.DateTime 2006,12,25

Access Properties/Invoke Methods


$d.DayOfWeek $d.AddDays(-30)
Allows admins to easily access and leverage a huge API set because of scriptability, utilities and formatting

Access Statics
[DateTime]::Now [DateTime]::IsLeapYear(2006)

PowerShell provides native XML support Native datatype


$x=*xml+"<a><b><c>TEST</c></b></a> $b =[xml](type c:\i386\mssecure.xml)

Native syntax to access data view of properties


$b.BulletinDataStore.Bulletins.Bulletin[0]

Access to XML methods


$b.BulletinDataStore.SelectNodes(//Patch)

XML properties available through PSBase property


$b.BulletinDataStore.PSBase.innerXml

Calling into .NET framework


Use .NET types in your scripts
PS C:\> echo $([DateTime]::Now)

Call into .NET directly


PS C:\> [System.Reflection.Assembly]:: LoadWithPartialName("System.Windows.Forms") PS C:\> [System.Windows.Forms.MessageBox]::Show("Hello)

Vous aimerez peut-être aussi