Windows Powershell– Every SysAdmin can build scripts!
Govindaraj RanganTechnology StrategistMicrosoft India
Agenda
Introduction to Windows Powershell
Scripting with Windows Powershell
Working with Objects (WMI, COM, .NET)
Scripting Best Practices
Agenda
Introduction to Windows Powershell
Scripting with Windows Powershell
Working with Objects (WMI, COM, .NET)
Scripting Best Practices
Windows Powershell - Overview
Interactive ShellRich Scripting EnvironmentObject OrientedExtensibleSecureMore than everything, EASY!
Architecture
Platform and Application Functionality
as COM and .NET Objects
Windows PowerShell Cmdlets
MMC Snap-In ScriptsInteractive Shell
Interfaces such as WMI, ADSI
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
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
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”
Agenda
Introduction to Windows Powershell
Scripting with Windows Powershell
Working with Objects (WMI, COM, .NET)
Scripting Best Practices
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”
OperatorsArithmetic
+, -, *, /, %Assignment
=, +=, -=, *=, /=, %=Conditional
-gt, -lt, -ge, -le, -ne, -eq, -containsAppend i or c for case insensitive or sensitive operations
String+, *, -replace, -match, -like
Constructs
If (condition) {# do something
} ElseIf {# do something
} Else {# do something
}
Constructs
For ($i = 0; $i –lt 10; $i++) {# do somethingif ($i –eq 5) {
break}
}
Constructs
Foreach ($item in collection) {# Do something to the itemif ($item –eq “a value”) {
break}
}
ConstructsSwitch (variable) {
“value1” { #do something}“value2” { #do something}“value3” { #do something}
}
Switch –regex|-wildcard (variable) {“.*?” { #do something}
}
Functions
function take_all_args {write-host $Args[0]
}
function take_sp_args ([string]$label = “t”){
# do something}
Build a script to identify IP addresses that are currently in use in a given subnet, using a simple ping test
demo
Agenda
Introduction to Windows Powershell
Scripting with Windows Powershell
Working with Objects (WMI, COM, .NET)
Scripting Best Practices
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
Working with WMIGet free hard disk space availableGet the amount of RAM installed
demo
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"
Working with Excel – Make an Excel report of Software Installed on a given machine
demo
.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”);
Getting user credentials using a dialog box.NET Namespace: System.Windows.Forms
demo
Agenda
Introduction to Windows Powershell
Scripting with Windows Powershell
Working with Objects (WMI, COM, .NET)
Scripting Best Practices
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
Powershell Resources
Powershell Download link: http://www.microsoft.com/downloads/details.aspx?FamilyID=c913aeab-d7b4-4bb1-a958-ee6d7fe307bc&displaylang=en
Powershell Blog:http://blogs.msdn.com/powershell/
धन्यवा�दઆભા�ર ধন্য�বা�দ
ਧੰ�ਨਵਾ�ਦ
ଧନ୍ୟ�ବା�ଦ
நன்றி�
ధన్య�వాదాలు� ಧನ್ಯ�ವಾ�ದಗಳು
നി�ങ്ങള്ക്ക്� നിന്ദി�
question & answer
© 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.