Powershell Tech Ed2009

32

Transcript of Powershell Tech Ed2009

Page 1: Powershell Tech Ed2009
Page 2: Powershell Tech Ed2009

Windows Powershell– Every SysAdmin can build scripts!

Govindaraj RanganTechnology StrategistMicrosoft India

Page 3: Powershell Tech Ed2009

Agenda

Introduction to Windows Powershell

Scripting with Windows Powershell

Working with Objects (WMI, COM, .NET)

Scripting Best Practices

Page 4: Powershell Tech Ed2009

Agenda

Introduction to Windows Powershell

Scripting with Windows Powershell

Working with Objects (WMI, COM, .NET)

Scripting Best Practices

Page 5: Powershell Tech Ed2009

Windows Powershell - Overview

Interactive ShellRich Scripting EnvironmentObject OrientedExtensibleSecureMore than everything, EASY!

Page 6: Powershell Tech Ed2009

Architecture

Platform and Application Functionality

as COM and .NET Objects

Windows PowerShell Cmdlets

MMC Snap-In ScriptsInteractive Shell

Interfaces such as WMI, ADSI

Page 7: Powershell Tech Ed2009

CmdLet Syntax

Status Name DisplayName------ ---- ----------- Stopped NetLogon NetLogonRunning Netman Network Connections

PS> get-service –name “*net*”

Verb NounName

ArgumentString

Command Parameter

Property Names

Property Values

Page 8: Powershell Tech Ed2009

Powershell Security

Powershell not associated with .PS1Doesn’t run script by Default

Does not run scripts without a pathYou need to autograph your script

Execution PolicyRestricted, Allsigned, Remote-signed, Unrestricted

Standard parameters like “-whatif”, “-confirm” to save you from making accidental changesRead-Host -assecurestring

Page 9: Powershell Tech Ed2009

Common CmdLetsPS C:\> Get-Command

CommandType Name Definition ----------- ---- --------- Function A: Set-Location A: Cmdlet Add-Computer Add-Computer [[-ComputerName] <String[]>] [-Do...Cmdlet Add-Content Add-Content [-Path] <String[]> [-Value] <Objec...

PS C:\> Get-Help Get-Command

PS C:\> Get-Process

PS C:\> Get-Process | Where-Object {$_.CPU –gt 100}

PS C:\> Get-Service

PS C:\> Get-EventLog

PS C:\> $var = Read-Host

PS C:\> Write-Host $var

PS C:\> Restart-Computer –ComputerName “MYBOSSPC”

Page 10: Powershell Tech Ed2009

Introducing Windows PowershellFew Commonly Used CmdLets

demo

Page 11: Powershell Tech Ed2009

Agenda

Introduction to Windows Powershell

Scripting with Windows Powershell

Working with Objects (WMI, COM, .NET)

Scripting Best Practices

Page 12: Powershell Tech Ed2009

Variables$ represents variable

$txt = get-content “C:\test.txt”Type determined based on usageStrong typing: [int] $nConstants: Set-Variable pi 3.14 –option Constant

Arrays$arr = @(1,2,3). $arr[0] returns 1

Associative Arrays (Hashtables)$marks = @{ram=“100”;ravan=“0”}$marks.ram returns “100”$marks[“ram”] returns “100”

Page 13: Powershell Tech Ed2009

OperatorsArithmetic

+, -, *, /, %Assignment

=, +=, -=, *=, /=, %=Conditional

-gt, -lt, -ge, -le, -ne, -eq, -containsAppend i or c for case insensitive or sensitive operations

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

Page 14: Powershell Tech Ed2009

Constructs

If (condition) {# do something

} ElseIf {# do something

} Else {# do something

}

Page 15: Powershell Tech Ed2009

Constructs

For ($i = 0; $i –lt 10; $i++) {# do somethingif ($i –eq 5) {

break}

}

Page 16: Powershell Tech Ed2009

Constructs

Foreach ($item in collection) {# Do something to the itemif ($item –eq “a value”) {

break}

}

Page 17: Powershell Tech Ed2009

ConstructsSwitch (variable) {

“value1” { #do something}“value2” { #do something}“value3” { #do something}

}

Switch –regex|-wildcard (variable) {“.*?” { #do something}

}

Page 18: Powershell Tech Ed2009

Functions

function take_all_args {write-host $Args[0]

}

function take_sp_args ([string]$label = “t”){

# do something}

Page 19: Powershell Tech Ed2009

Build a script to identify IP addresses that are currently in use in a given subnet, using a simple ping test

demo

Page 20: Powershell Tech Ed2009

Agenda

Introduction to Windows Powershell

Scripting with Windows Powershell

Working with Objects (WMI, COM, .NET)

Scripting Best Practices

Page 21: Powershell Tech Ed2009

WMI ObjectsWindows Management Instrumentation (WMI)

◦WMI is a core technology for Windows system administration ◦ It exposes a wide range of information in a uniform manner.

Get-WmiObject cmdlet

Listing WMI classes◦ Get-WmiObject -List◦ Get-WmiObject -list -ComputerName cflabsql01

Getting WMI objects◦ Get-WmiObject -Class Win32_OperatingSystem◦ Get-WmiObject -class Win32_LogicalDisk◦ Get-WmiObject -Class Win32_Service | Select-Object -Property

Status,Name,DisplayName

Page 22: Powershell Tech Ed2009

Working with WMIGet free hard disk space availableGet the amount of RAM installed

demo

Page 23: Powershell Tech Ed2009

COM ObjectsCreate a COM object using New-Object◦> $xl= New-Object -ComObject Excel.Application

Reflect against properties/methods◦> $xl |get-member

Access properties/methods◦> $xl.Visible = “True”

Drill down into Excel object model◦> $wb = $xl.Workbooks.Add()◦> $ws = $xl.Worksheets.Item(1)◦> $ws.Cells.Item(1,1) = "TEST“◦> $ws.Cells.Item(1,1).Font.Bold = "True“◦> $ws.Cells.Item(1,1).Font.Size = 24◦$xl.Workbooks.Add().Worksheets.Item(1).Cells.Item(1,1) =

"HELLO"

Page 24: Powershell Tech Ed2009

Working with Excel – Make an Excel report of Software Installed on a given machine

demo

Page 25: Powershell Tech Ed2009

.NET ObjectsCreating .Net objects

$f = New-Object System.Windows.Forms.Form

Inspecting properties-methods $f|Get-Member

Accessing properties-methods $f.Text = "Give me the username and password“

Adding Controls to the Parent Object (Form)Create control object:

$OKButton = New-object System.Windows.Forms.ButtonAdd control to Parent:

$f.Controls.Add($OKButton)

Load any assembly and use its objects◦ [Reflection.Assembly]::LoadFrom(“…\abc.dll”);

Page 26: Powershell Tech Ed2009

Getting user credentials using a dialog box.NET Namespace: System.Windows.Forms

demo

Page 27: Powershell Tech Ed2009

Agenda

Introduction to Windows Powershell

Scripting with Windows Powershell

Working with Objects (WMI, COM, .NET)

Scripting Best Practices

Page 28: Powershell Tech Ed2009

Scripting Best PracticesUse sensible variable namesIndent within constructsUse Source ControlAvoid aliases within ScriptsUse as descriptive comments as possibleUse Functions and Script blocks to reduce the number of lines of codeTest thoroughly for boundary conditions before running in productionCapture and report all logical errors

Page 30: Powershell Tech Ed2009

धन्यवा�दઆભા�ર ধন্য�বা�দ

ਧੰ�ਨਵਾ�ਦ

ଧନ୍ୟ�ବା�ଦ

நன்றி�

ధన్య�వాదాలు� ಧನ್ಯ�ವಾ�ದಗಳು

നി�ങ്ങള്‍‌ക്ക്� നിന്ദി�

Page 31: Powershell Tech Ed2009

question & answer

Page 32: Powershell Tech Ed2009

© 2009 Microsoft Corporation. All rights reserved. Microsoft, Windows, Windows Vista and other product names are or may be registered trademarks and/or trademarks in the U.S. and/or other countries.The information herein is for informational purposes only and represents the current view of Microsoft Corporation as of the date of this presentation. Because Microsoft must respond to changing market conditions, it should not be interpreted to be a commitment on the part of Microsoft, and Microsoft cannot guarantee the accuracy of any information provided after the date of this presentation. MICROSOFT MAKES NO WARRANTIES, EXPRESS,

IMPLIED OR STATUTORY, AS TO THE INFORMATION IN THIS PRESENTATION.