SlideShare une entreprise Scribd logo
1  sur  32
Govindaraj Rangan
Technology Strategist
Microsoft 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 Shell
 Rich Scripting Environment
 Object Oriented
 Extensible
 Secure
 More than everything, EASY! 
Architecture

     MMC Snap-In       Interactive Shell          Scripts


                 Windows PowerShell Cmdlets


     Platform and Application
                                       Interfaces such as
           Functionality
                                           WMI, ADSI
     as COM and .NET Objects
CmdLet Syntax
                                             Argument
                              Name             String
      Verb   Noun

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

        Command                      Parameter

                         Property Names


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

                         Property Values
Powershell Security
 Powershell not associated with .PS1
    Doesn’t run script by Default
 Does not run scripts without a path
 You need to autograph your script
    Execution Policy
      Restricted, Allsigned, Remote-signed, Unrestricted
 Standard parameters like “-whatif”, “-confirm”
 to save you from making accidental changes
 Read-Host -assecurestring
Common CmdLets
PS 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”
Introducing Windows Powershell
Few Commonly Used CmdLets
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 usage
    Strong typing: [int] $n
    Constants: 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”
Operators
 Arithmetic
    +, -, *, /, %
 Assignment
    =, +=, -=, *=, /=, %=
 Conditional
    -gt, -lt, -ge, -le, -ne, -eq, -contains
    Append 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 something
  if ($i –eq 5) {
      break
  }
}
Constructs
Foreach ($item in collection) {
  # Do something to the item
  if ($item –eq “a value”) ,
      break
  }
}
Constructs
Switch (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
Agenda

 Introduction to Windows Powershell

 Scripting with Windows Powershell

 Working with Objects (WMI, COM, .NET)

 Scripting Best Practices
WMI Objects
   Windows 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 WMI
   Get free hard disk space available
   Get the amount of RAM installed
COM Objects
   Create 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) = quot;TEST“
    ◦   > $ws.Cells.Item(1,1).Font.Bold = quot;True“
    ◦   > $ws.Cells.Item(1,1).Font.Size = 24
    ◦   $xl.Workbooks.Add().Worksheets.Item(1).Cells.Item(1,1) =
        quot;HELLOquot;
Working with Excel – Make an Excel
report of Software Installed on a given
machine
.NET Objects
   Creating .Net objects
        $f = New-Object System.Windows.Forms.Form

   Inspecting properties-methods
        $f|Get-Member

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

   Adding Controls to the Parent Object (Form)
      Create control object:
           $OKButton = New-object System.Windows.Forms.Button
        Add 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
Agenda

 Introduction to Windows Powershell

 Scripting with Windows Powershell

 Working with Objects (WMI, COM, .NET)

 Scripting Best Practices
Scripting Best Practices
  Use sensible variable names
  Indent within constructs
  Use Source Control
  Avoid aliases within Scripts
  Use as descriptive comments as possible
  Use Functions and Script blocks to reduce the
  number of lines of code
  Test thoroughly for boundary conditions before
  running in production
  Capture 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/
© 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.

Contenu connexe

Tendances

Build Lightweight Web Module
Build Lightweight Web ModuleBuild Lightweight Web Module
Build Lightweight Web Module
Morgan Cheng
 
Gearman jobqueue
Gearman jobqueueGearman jobqueue
Gearman jobqueue
Magento Dev
 
Unit testing JavaScript using Mocha and Node
Unit testing JavaScript using Mocha and NodeUnit testing JavaScript using Mocha and Node
Unit testing JavaScript using Mocha and Node
Josh Mock
 
Web2py Code Lab
Web2py Code LabWeb2py Code Lab
Web2py Code Lab
Colin Su
 

Tendances (20)

Php server variables
Php server variablesPhp server variables
Php server variables
 
Currying and Partial Function Application (PFA)
Currying and Partial Function Application (PFA)Currying and Partial Function Application (PFA)
Currying and Partial Function Application (PFA)
 
Build Lightweight Web Module
Build Lightweight Web ModuleBuild Lightweight Web Module
Build Lightweight Web Module
 
Impact of the New ORM on Your Modules
Impact of the New ORM on Your ModulesImpact of the New ORM on Your Modules
Impact of the New ORM on Your Modules
 
Php pattern matching
Php pattern matchingPhp pattern matching
Php pattern matching
 
ES6, 잘 쓰고 계시죠?
ES6, 잘 쓰고 계시죠?ES6, 잘 쓰고 계시죠?
ES6, 잘 쓰고 계시죠?
 
Php functions
Php functionsPhp functions
Php functions
 
My app is secure... I think
My app is secure... I thinkMy app is secure... I think
My app is secure... I think
 
Gearman jobqueue
Gearman jobqueueGearman jobqueue
Gearman jobqueue
 
New Framework - ORM
New Framework - ORMNew Framework - ORM
New Framework - ORM
 
PowerShell Fundamentals
PowerShell FundamentalsPowerShell Fundamentals
PowerShell Fundamentals
 
Programming with Python and PostgreSQL
Programming with Python and PostgreSQLProgramming with Python and PostgreSQL
Programming with Python and PostgreSQL
 
Practical Celery
Practical CeleryPractical Celery
Practical Celery
 
Filling the flask
Filling the flaskFilling the flask
Filling the flask
 
Graphql, REST and Apollo
Graphql, REST and ApolloGraphql, REST and Apollo
Graphql, REST and Apollo
 
Unit testing JavaScript using Mocha and Node
Unit testing JavaScript using Mocha and NodeUnit testing JavaScript using Mocha and Node
Unit testing JavaScript using Mocha and Node
 
Workshop 10: ECMAScript 6
Workshop 10: ECMAScript 6Workshop 10: ECMAScript 6
Workshop 10: ECMAScript 6
 
Python postgre sql a wonderful wedding
Python postgre sql   a wonderful weddingPython postgre sql   a wonderful wedding
Python postgre sql a wonderful wedding
 
And now you have two problems. Ruby regular expressions for fun and profit by...
And now you have two problems. Ruby regular expressions for fun and profit by...And now you have two problems. Ruby regular expressions for fun and profit by...
And now you have two problems. Ruby regular expressions for fun and profit by...
 
Web2py Code Lab
Web2py Code LabWeb2py Code Lab
Web2py Code Lab
 

En vedette

PowerShell Scripting and Modularization (TechMentor Fall 2011)
PowerShell Scripting and Modularization (TechMentor Fall 2011)PowerShell Scripting and Modularization (TechMentor Fall 2011)
PowerShell Scripting and Modularization (TechMentor Fall 2011)
Concentrated Technology
 
Advanced Tools & Scripting with PowerShell 3.0 Jump Start - Certificate
Advanced Tools & Scripting with PowerShell 3.0 Jump Start - CertificateAdvanced Tools & Scripting with PowerShell 3.0 Jump Start - Certificate
Advanced Tools & Scripting with PowerShell 3.0 Jump Start - Certificate
Don Reese
 

En vedette (11)

PowerShell Scripting and Modularization (TechMentor Fall 2011)
PowerShell Scripting and Modularization (TechMentor Fall 2011)PowerShell Scripting and Modularization (TechMentor Fall 2011)
PowerShell Scripting and Modularization (TechMentor Fall 2011)
 
Advanced Tools & Scripting with PowerShell 3.0 Jump Start - Certificate
Advanced Tools & Scripting with PowerShell 3.0 Jump Start - CertificateAdvanced Tools & Scripting with PowerShell 3.0 Jump Start - Certificate
Advanced Tools & Scripting with PowerShell 3.0 Jump Start - Certificate
 
No-script PowerShell v2
No-script PowerShell v2No-script PowerShell v2
No-script PowerShell v2
 
Windows PowerShell
Windows PowerShellWindows PowerShell
Windows PowerShell
 
Mastering IntelliTrace in Development and Production
Mastering IntelliTrace in Development and ProductionMastering IntelliTrace in Development and Production
Mastering IntelliTrace in Development and Production
 
Powershell Demo Presentation
Powershell Demo PresentationPowershell Demo Presentation
Powershell Demo Presentation
 
Basic PowerShell Toolmaking - Spiceworld 2016 session
Basic PowerShell Toolmaking - Spiceworld 2016 sessionBasic PowerShell Toolmaking - Spiceworld 2016 session
Basic PowerShell Toolmaking - Spiceworld 2016 session
 
Gerenciamento de Servidores com PowerShell 3.0
Gerenciamento de Servidores com PowerShell 3.0Gerenciamento de Servidores com PowerShell 3.0
Gerenciamento de Servidores com PowerShell 3.0
 
PowerShell for Cyber Warriors - Bsides Knoxville 2016
PowerShell for Cyber Warriors - Bsides Knoxville 2016PowerShell for Cyber Warriors - Bsides Knoxville 2016
PowerShell for Cyber Warriors - Bsides Knoxville 2016
 
Building an Empire with PowerShell
Building an Empire with PowerShellBuilding an Empire with PowerShell
Building an Empire with PowerShell
 
An Introduction to Windows PowerShell
An Introduction to Windows PowerShellAn Introduction to Windows PowerShell
An Introduction to Windows PowerShell
 

Similaire à Powershell Tech Ed2009

CiklumJavaSat_15112011:Alex Kruk VMForce
CiklumJavaSat_15112011:Alex Kruk VMForceCiklumJavaSat_15112011:Alex Kruk VMForce
CiklumJavaSat_15112011:Alex Kruk VMForce
Ciklum Ukraine
 
Windows Remote Management - EN
Windows Remote Management - ENWindows Remote Management - EN
Windows Remote Management - EN
Kirill Nikolaev
 
Automating PowerShell with SharePoint
Automating PowerShell with SharePointAutomating PowerShell with SharePoint
Automating PowerShell with SharePoint
Talbott Crowell
 

Similaire à Powershell Tech Ed2009 (20)

Powershell Seminar @ ITWorx CuttingEdge Club
Powershell Seminar @ ITWorx CuttingEdge ClubPowershell Seminar @ ITWorx CuttingEdge Club
Powershell Seminar @ ITWorx CuttingEdge Club
 
Introduction to PowerShell
Introduction to PowerShellIntroduction to PowerShell
Introduction to PowerShell
 
Windows Server 2008 (PowerShell Scripting Uygulamaları)
Windows Server 2008 (PowerShell Scripting Uygulamaları)Windows Server 2008 (PowerShell Scripting Uygulamaları)
Windows Server 2008 (PowerShell Scripting Uygulamaları)
 
General Principles of Web Security
General Principles of Web SecurityGeneral Principles of Web Security
General Principles of Web Security
 
NIIT ISAS Q5 Report - Windows PowerShell
NIIT ISAS Q5 Report - Windows PowerShellNIIT ISAS Q5 Report - Windows PowerShell
NIIT ISAS Q5 Report - Windows PowerShell
 
PowerShell Technical Overview
PowerShell Technical OverviewPowerShell Technical Overview
PowerShell Technical Overview
 
PowerShell for SharePoint Developers
PowerShell for SharePoint DevelopersPowerShell for SharePoint Developers
PowerShell for SharePoint Developers
 
Javascript 1
Javascript 1Javascript 1
Javascript 1
 
Get-Help: An intro to PowerShell and how to Use it for Evil
Get-Help: An intro to PowerShell and how to Use it for EvilGet-Help: An intro to PowerShell and how to Use it for Evil
Get-Help: An intro to PowerShell and how to Use it for Evil
 
eXo SEA - JavaScript Introduction Training
eXo SEA - JavaScript Introduction TrainingeXo SEA - JavaScript Introduction Training
eXo SEA - JavaScript Introduction Training
 
CiklumJavaSat_15112011:Alex Kruk VMForce
CiklumJavaSat_15112011:Alex Kruk VMForceCiklumJavaSat_15112011:Alex Kruk VMForce
CiklumJavaSat_15112011:Alex Kruk VMForce
 
Introduction to powershell
Introduction to powershellIntroduction to powershell
Introduction to powershell
 
Windows Remote Management - EN
Windows Remote Management - ENWindows Remote Management - EN
Windows Remote Management - EN
 
Introduction to PowerShell
Introduction to PowerShellIntroduction to PowerShell
Introduction to PowerShell
 
Bigger Stronger Faster
Bigger Stronger FasterBigger Stronger Faster
Bigger Stronger Faster
 
Taking Jenkins Pipeline to the Extreme
Taking Jenkins Pipeline to the ExtremeTaking Jenkins Pipeline to the Extreme
Taking Jenkins Pipeline to the Extreme
 
Protractor framework – how to make stable e2e tests for Angular applications
Protractor framework – how to make stable e2e tests for Angular applicationsProtractor framework – how to make stable e2e tests for Angular applications
Protractor framework – how to make stable e2e tests for Angular applications
 
Automating PowerShell with SharePoint
Automating PowerShell with SharePointAutomating PowerShell with SharePoint
Automating PowerShell with SharePoint
 
Power shell training
Power shell trainingPower shell training
Power shell training
 
An introduction-to-windows-powershell-1193007253563204-3
An introduction-to-windows-powershell-1193007253563204-3An introduction-to-windows-powershell-1193007253563204-3
An introduction-to-windows-powershell-1193007253563204-3
 

Plus de rsnarayanan

Kevin Ms Web Platform
Kevin Ms Web PlatformKevin Ms Web Platform
Kevin Ms Web Platform
rsnarayanan
 
Harish Understanding Aspnet
Harish Understanding AspnetHarish Understanding Aspnet
Harish Understanding Aspnet
rsnarayanan
 
Harish Aspnet Dynamic Data
Harish Aspnet Dynamic DataHarish Aspnet Dynamic Data
Harish Aspnet Dynamic Data
rsnarayanan
 
Harish Aspnet Deployment
Harish Aspnet DeploymentHarish Aspnet Deployment
Harish Aspnet Deployment
rsnarayanan
 
Whats New In Sl3
Whats New In Sl3Whats New In Sl3
Whats New In Sl3
rsnarayanan
 
Silverlight And .Net Ria Services – Building Lob And Business Applications Wi...
Silverlight And .Net Ria Services – Building Lob And Business Applications Wi...Silverlight And .Net Ria Services – Building Lob And Business Applications Wi...
Silverlight And .Net Ria Services – Building Lob And Business Applications Wi...
rsnarayanan
 
Advanced Silverlight
Advanced SilverlightAdvanced Silverlight
Advanced Silverlight
rsnarayanan
 
Occasionally Connected Systems
Occasionally Connected SystemsOccasionally Connected Systems
Occasionally Connected Systems
rsnarayanan
 
Developing Php Applications Using Microsoft Software And Services
Developing Php Applications Using Microsoft Software And ServicesDeveloping Php Applications Using Microsoft Software And Services
Developing Php Applications Using Microsoft Software And Services
rsnarayanan
 
Build Mission Critical Applications On The Microsoft Platform Using Eclipse J...
Build Mission Critical Applications On The Microsoft Platform Using Eclipse J...Build Mission Critical Applications On The Microsoft Platform Using Eclipse J...
Build Mission Critical Applications On The Microsoft Platform Using Eclipse J...
rsnarayanan
 
J Query The Write Less Do More Javascript Library
J Query   The Write Less Do More Javascript LibraryJ Query   The Write Less Do More Javascript Library
J Query The Write Less Do More Javascript Library
rsnarayanan
 
Ms Sql Business Inteligence With My Sql
Ms Sql Business Inteligence With My SqlMs Sql Business Inteligence With My Sql
Ms Sql Business Inteligence With My Sql
rsnarayanan
 
Windows 7 For Developers
Windows 7 For DevelopersWindows 7 For Developers
Windows 7 For Developers
rsnarayanan
 
What Is New In Wpf 3.5 Sp1
What Is New In Wpf 3.5 Sp1What Is New In Wpf 3.5 Sp1
What Is New In Wpf 3.5 Sp1
rsnarayanan
 
Ux For Developers
Ux For DevelopersUx For Developers
Ux For Developers
rsnarayanan
 
A Lap Around Internet Explorer 8
A Lap Around Internet Explorer 8A Lap Around Internet Explorer 8
A Lap Around Internet Explorer 8
rsnarayanan
 

Plus de rsnarayanan (20)

Walther Aspnet4
Walther Aspnet4Walther Aspnet4
Walther Aspnet4
 
Walther Ajax4
Walther Ajax4Walther Ajax4
Walther Ajax4
 
Kevin Ms Web Platform
Kevin Ms Web PlatformKevin Ms Web Platform
Kevin Ms Web Platform
 
Harish Understanding Aspnet
Harish Understanding AspnetHarish Understanding Aspnet
Harish Understanding Aspnet
 
Walther Mvc
Walther MvcWalther Mvc
Walther Mvc
 
Harish Aspnet Dynamic Data
Harish Aspnet Dynamic DataHarish Aspnet Dynamic Data
Harish Aspnet Dynamic Data
 
Harish Aspnet Deployment
Harish Aspnet DeploymentHarish Aspnet Deployment
Harish Aspnet Deployment
 
Whats New In Sl3
Whats New In Sl3Whats New In Sl3
Whats New In Sl3
 
Silverlight And .Net Ria Services – Building Lob And Business Applications Wi...
Silverlight And .Net Ria Services – Building Lob And Business Applications Wi...Silverlight And .Net Ria Services – Building Lob And Business Applications Wi...
Silverlight And .Net Ria Services – Building Lob And Business Applications Wi...
 
Advanced Silverlight
Advanced SilverlightAdvanced Silverlight
Advanced Silverlight
 
Netcf Gc
Netcf GcNetcf Gc
Netcf Gc
 
Occasionally Connected Systems
Occasionally Connected SystemsOccasionally Connected Systems
Occasionally Connected Systems
 
Developing Php Applications Using Microsoft Software And Services
Developing Php Applications Using Microsoft Software And ServicesDeveloping Php Applications Using Microsoft Software And Services
Developing Php Applications Using Microsoft Software And Services
 
Build Mission Critical Applications On The Microsoft Platform Using Eclipse J...
Build Mission Critical Applications On The Microsoft Platform Using Eclipse J...Build Mission Critical Applications On The Microsoft Platform Using Eclipse J...
Build Mission Critical Applications On The Microsoft Platform Using Eclipse J...
 
J Query The Write Less Do More Javascript Library
J Query   The Write Less Do More Javascript LibraryJ Query   The Write Less Do More Javascript Library
J Query The Write Less Do More Javascript Library
 
Ms Sql Business Inteligence With My Sql
Ms Sql Business Inteligence With My SqlMs Sql Business Inteligence With My Sql
Ms Sql Business Inteligence With My Sql
 
Windows 7 For Developers
Windows 7 For DevelopersWindows 7 For Developers
Windows 7 For Developers
 
What Is New In Wpf 3.5 Sp1
What Is New In Wpf 3.5 Sp1What Is New In Wpf 3.5 Sp1
What Is New In Wpf 3.5 Sp1
 
Ux For Developers
Ux For DevelopersUx For Developers
Ux For Developers
 
A Lap Around Internet Explorer 8
A Lap Around Internet Explorer 8A Lap Around Internet Explorer 8
A Lap Around Internet Explorer 8
 

Dernier

Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
vu2urc
 

Dernier (20)

Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Tech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdfTech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdf
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 

Powershell Tech Ed2009

  • 1.
  • 3. Agenda Introduction to Windows Powershell Scripting with Windows Powershell Working with Objects (WMI, COM, .NET) Scripting Best Practices
  • 4. Agenda Introduction to Windows Powershell Scripting with Windows Powershell Working with Objects (WMI, COM, .NET) Scripting Best Practices
  • 5. Windows Powershell - Overview Interactive Shell Rich Scripting Environment Object Oriented Extensible Secure More than everything, EASY! 
  • 6. Architecture MMC Snap-In Interactive Shell Scripts Windows PowerShell Cmdlets Platform and Application Interfaces such as Functionality WMI, ADSI as COM and .NET Objects
  • 7. CmdLet Syntax Argument Name String Verb Noun PS> get-service –name “*net*” Command Parameter Property Names Status Name DisplayName ------ ---- ----------- Stopped NetLogon NetLogon Running Netman Network Connections Property Values
  • 8. Powershell Security Powershell not associated with .PS1 Doesn’t run script by Default Does not run scripts without a path You need to autograph your script Execution Policy Restricted, Allsigned, Remote-signed, Unrestricted Standard parameters like “-whatif”, “-confirm” to save you from making accidental changes Read-Host -assecurestring
  • 9. Common CmdLets PS 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”
  • 10. Introducing Windows Powershell Few Commonly Used CmdLets
  • 11. Agenda Introduction to Windows Powershell Scripting with Windows Powershell Working with Objects (WMI, COM, .NET) Scripting Best Practices
  • 12. Variables $ represents variable $txt = get-content “C:test.txt” Type determined based on usage Strong typing: [int] $n Constants: 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”
  • 13. Operators Arithmetic +, -, *, /, % Assignment =, +=, -=, *=, /=, %= Conditional -gt, -lt, -ge, -le, -ne, -eq, -contains Append i or c for case insensitive or sensitive operations String +, *, -replace, -match, -like
  • 14. Constructs If (condition) { # do something } ElseIf { # do something } Else { # do something }
  • 15. Constructs For ($i = 0; $i –lt 10; $i++) { # do something if ($i –eq 5) { break } }
  • 16. Constructs Foreach ($item in collection) { # Do something to the item if ($item –eq “a value”) , break } }
  • 17. Constructs Switch (variable) { “value1” , #do something- “value2” , #do something- “value3” , #do something- } Switch –regex|-wildcard (variable) { “.*?” , #do something- }
  • 18. Functions function take_all_args { write-host $Args[0] } function take_sp_args (*string+$label = “t”) { # do something }
  • 19. Build a script to identify IP addresses that are currently in use in a given subnet, using a simple ping test
  • 20. Agenda Introduction to Windows Powershell Scripting with Windows Powershell Working with Objects (WMI, COM, .NET) Scripting Best Practices
  • 21. WMI Objects  Windows 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
  • 22. Working with WMI Get free hard disk space available Get the amount of RAM installed
  • 23. COM Objects  Create 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) = quot;TEST“ ◦ > $ws.Cells.Item(1,1).Font.Bold = quot;True“ ◦ > $ws.Cells.Item(1,1).Font.Size = 24 ◦ $xl.Workbooks.Add().Worksheets.Item(1).Cells.Item(1,1) = quot;HELLOquot;
  • 24. Working with Excel – Make an Excel report of Software Installed on a given machine
  • 25. .NET Objects  Creating .Net objects  $f = New-Object System.Windows.Forms.Form  Inspecting properties-methods  $f|Get-Member  Accessing properties-methods  $f.Text = quot;Give me the username and password“  Adding Controls to the Parent Object (Form)  Create control object:  $OKButton = New-object System.Windows.Forms.Button  Add control to Parent:  $f.Controls.Add($OKButton)  Load any assembly and use its objects ◦ [Reflection.Assembly]::LoadFrom(“…abc.dll”);
  • 26. Getting user credentials using a dialog box .NET Namespace: System.Windows.Forms
  • 27. Agenda Introduction to Windows Powershell Scripting with Windows Powershell Working with Objects (WMI, COM, .NET) Scripting Best Practices
  • 28. Scripting Best Practices Use sensible variable names Indent within constructs Use Source Control Avoid aliases within Scripts Use as descriptive comments as possible Use Functions and Script blocks to reduce the number of lines of code Test thoroughly for boundary conditions before running in production Capture and report all logical errors
  • 29. 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/
  • 30.
  • 31.
  • 32. © 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.

Notes de l'éditeur

  1. Get-HelpGet-CommandGet-ProcessGet-Service
  2. Get-HelpGet-CommandGet-ProcessGet-Service
  3. Get-HelpGet-CommandGet-ProcessGet-Service
  4. Get-HelpGet-CommandGet-ProcessGet-Service