No-script PowerShell v2


Published on

Published in: Technology
  • Be the first to comment

  • Be the first to like this

No Downloads
Total views
On SlideShare
From Embeds
Number of Embeds
Embeds 0
No embeds

No notes for slide
  • MGB 2003 © 2003 Microsoft Corporation. All rights reserved. This presentation is for informational purposes only. Microsoft makes no warranties, express or implied, in this summary.
  • Windows PowerShell 101 Based upon Windows PowerShell: TFM by Jones and Hicks Copyright ©2007 SAPIEN Technologies, Inc. Here's how script signing and the execution policy work. You've *got your PowerShell script that you want to run, and you've got a *computer that you want to copy the script to so that you can run the script there. Simple enough. Let's say you've got your Execution Policy set to AllSigned. Well, if your script isn't signed, then PowerShell isn't going to run it. So you're going to need to go to a *certificate server, either one internal to your network or a commercial one, and obtain what's called a *code-signing certificate. After the certification authority – that's the folks who own the certificate server – verify your identity in some way, they'll *issue you the certificate, and you'll use it to digitally sign your script. PowerShell knows how to do that once the certificate is installed on your local computer. *Once signed, you can copy your script to the computer where you want it to run. When you ask the computer to *run the script, it performs three *checks: First checks to see if it's signed. *Well, it is. So now it checks to see if the signature is intact, meaning that the script hasn't been changed since it was signed. And that check *passes. Finally, it *checks to see if it trusts the certification authority who issued the certificate in the first place. Basically, the computer is asking, "do I trust this CA to have accurately verified the identity of the script author before they have him a certificate?" *Provided the computer trusts the certificate authority, *the third check will pass, and the script will run. For more details on how to sign a script, consult the PowerShell docs, Windows PowerShell: TFM, or use SAPIEN PrimalScript Professional or Enterprise Editions, which have script-signing functionality built right in.
  • MGB 2003 © 2003 Microsoft Corporation. All rights reserved. This presentation is for informational purposes only. Microsoft makes no warranties, express or implied, in this summary.
  • No-script PowerShell v2

    1. 1. The Windows PowerShell v2 No-Scripting Crash Course Don Jones Pre-requisites for this presentation: 1) Strong understanding of basic Windows administration Level: Intermediate
    2. 2. This slide deck was used in one of our many conference presentations. We hope you enjoy it, and invite you to use it within your own organization however you like. For more information on our company, including information on private classes and upcoming conference appearances, please visit our Web site, . For links to newly-posted decks, follow us on Twitter: @concentrateddon or @concentratdgreg This work is copyright ©Concentrated Technology, LLC
    3. 3. About the Instructor <ul><li>Don Jones </li></ul><ul><li>Contributing Editor, </li></ul><ul><li>IT author, consultant, and speaker </li></ul><ul><li>Co-founder of Concentrated Technology </li></ul><ul><li>Seven-time recipient of Microsoft ’s Most Valuable Professional (MVP) Award </li></ul><ul><li>Author and Editor-in-Chief for Realtime Publishers </li></ul><ul><li>Trainer for </li></ul>
    4. 4. Notes <ul><li>Sample Code </li></ul><ul><ul><li>I ’ll save as I go </li></ul></ul><ul><ul><li>I ’ll make everything available as a download from my Web site – details on the last slide </li></ul></ul><ul><ul><li>I ’ll also include a copy of this slide deck </li></ul></ul><ul><ul><li>Please… personal use only. </li></ul></ul><ul><li>Agenda </li></ul><ul><ul><li>This deck is really just a guide to make sure you have certain things in writing to take home </li></ul></ul><ul><ul><li>We might change up the order a bit, and you ’ll see a lot more than I list here </li></ul></ul>
    5. 5. The Agenda <ul><li>PowerShell backgrounder and crash course </li></ul><ul><li>Accomplishing real IT admin tasks using PowerShell </li></ul>
    6. 6. Resources <ul><li> New tech content every day (including PowerShell tips & series) </li></ul><ul><li> </li></ul><ul><li> / </li></ul><ul><li> </li></ul><ul><li>Blogs.Msdn.Com/PowerShell </li></ul>
    7. 7. If you ’re following along… <ul><li>Start-Transcript filename </li></ul><ul><ul><li>Records a transcript of everything you type in the shell, including output </li></ul></ul><ul><ul><li>Helps create a log of what you do here in class </li></ul></ul><ul><ul><li>Simple text file </li></ul></ul><ul><li>Stop-Transcript </li></ul>
    8. 8. What is Windows PowerShell? <ul><li>A command-line interface (CLI) used to administer Windows and other products and technologies… </li></ul><ul><li>… but also a new way of developing Windows and other products to be more manageable </li></ul><ul><li>An interactive shell as well as a simplified scripting language </li></ul>
    9. 9. Why a CLI? <ul><li>A GUI is great for creating one user, or modifying one server, or reconfiguring one service </li></ul><ul><li>Performing anything multiple times in a GUI becomes repetitive, boring, and error-prone </li></ul><ul><li>A CLI is inherently better when it comes to automating repetitive tasks </li></ul>
    10. 10. But the GUI can do mass administration! <ul><li>Tools (often third party) can be written to perform specific repetitive tasks… </li></ul><ul><li>… do you want to spend all your time hunting down, learning, and possibly paying for dozens of “point solution” tools? </li></ul><ul><li>A CLI provides a single way to do it all, in a consistent fashion </li></ul>
    11. 11. The Dark Ages of Administration Windows / Server Product Functionality (Services, Configuration Database, etc) Graphical User Interface for Administration (MMC Snap-Ins) COM Objects (DLLs) Command-Line Utilities WMI Provider Scripts (Batch, VBScript, etc.) The Missing Pieces
    12. 12. The Dark Ages ’ Problem <ul><li>Some command-line tools do some things </li></ul><ul><li>Some COM objects do some things </li></ul><ul><li>Some WMI providers do some things </li></ul><ul><li>Nothing does everything ! </li></ul><ul><li>Means learning many different tools, which all work differently </li></ul>
    13. 13. The PowerShell Age of Administration Windows / Server Product Functionality (Services, Configuration Database, etc) Microsoft .NET Framework Windows PowerShell Scripts GUI
    14. 14. The PowerShell Advantage <ul><li>Bring all functionality together in a single place (the CLI) </li></ul><ul><li>Expose the functionality in a way which can be automated (scripting) and used to “power” a GUI </li></ul><ul><li>Create that functionality in a consistent fashion (e.g., learn one way to do everything ) </li></ul>
    15. 15. How it Happens <ul><li>Microsoft builds new products so that their administrative functionality “lives” in PowerShell </li></ul><ul><li>GUI consoles just “sit on top” of PowerShell </li></ul><ul><li>Over time, more and more products become “fully exposed” in PowerShell </li></ul>
    16. 16. Fully PowerShell-ed Products <ul><li>Exchange Server 2007 </li></ul><ul><li>System Center Operations Manager 2007 </li></ul><ul><li>System Center Virtual Machine Manager </li></ul><ul><li>System Center Data Protection Manager </li></ul><ul><li>More coming… including non-Microsoft products! </li></ul><ul><li>Win2008 R2 adds significantly to the list </li></ul>
    17. 17. In the Meantime… <ul><li>PowerShell still connects to existing administrative functionality </li></ul><ul><ul><li>Windows Management Instrumentation </li></ul></ul><ul><ul><li>Microsoft .NET Framework </li></ul></ul><ul><ul><li>Component Object Model (COM) </li></ul></ul><ul><ul><li>Active Directory Services Interface (ADSI) </li></ul></ul><ul><li>Allows you to (partially) administer non-PowerShell technologies today </li></ul>
    18. 18. System Requirements <ul><li>Windows XP or later (ships with Windows Server 2008 as an optional component; installed by default in 2008R2 and Win7) </li></ul><ul><li>Microsoft .NET Framework v2.0 or later </li></ul><ul><li>Install everywhere (remote shell!) </li></ul>
    19. 19. Installing PowerShell <ul><li>Download from (if not included with your version of Windows) </li></ul><ul><li>Run installer </li></ul><ul><li>Installs to systemroot WindowsPowerShell </li></ul>
    20. 20. How it Works - Overview <ul><li>Cmdlets are the “command-line utilities” within PowerShell </li></ul><ul><li>They work with objects, not text, and can “plug into” one another to perform more complex tasks </li></ul><ul><li>“ Nicknames” called aliases make cmdlet names easier to type </li></ul><ul><li>Cmdlets can be “snapped in” to extend the shell’s functionality </li></ul>
    21. 21. Navigating your system <ul><li>You probably already know how to do this! </li></ul><ul><li>Start thinking of the commands you'd use to navigate your system using Cmd.exe </li></ul><ul><li>Or, if you prefer the commands you'd use in a Linux or Unix operating system </li></ul><ul><li>Quiz follows… </li></ul>
    22. 22. Same command… different parameters <ul><li>Try Dir /s </li></ul><ul><li>Doesn't work! </li></ul><ul><li>The command names are similar to what you're used to in Cmd.exe… </li></ul><ul><li>… but the way in which the commands work are significantly different </li></ul><ul><li>Fortunately, PowerShell can help you learn how to use the new commands </li></ul>
    23. 23. Asking for help <ul><li>PowerShell includes a robust built-in help system </li></ul><ul><li>Ask for help on any command using the Help keyword (or Man if you prefer) </li></ul><ul><li>Help accepts wildcards – lets you look up commands when you're not sure of their name </li></ul><ul><li>Provides a quick reference to the correct parameters and syntax </li></ul><ul><li>Add –online for latest version of help files </li></ul>
    24. 24. Single, consistent skill set <ul><li>If you know one set of commands to navigate one type of hierarchical file system… </li></ul><ul><li>… why not use the commands for other types of storage systems? </li></ul><ul><ul><li>The registry </li></ul></ul><ul><ul><li>The certificate store </li></ul></ul><ul><ul><li>Environment variables </li></ul></ul><ul><ul><li>Active Directory </li></ul></ul>
    25. 25. How it works <ul><li>PowerShell uses PSDrive Providers to connect to various storage systems </li></ul><ul><li>The providers adapt a storage system to look like a &quot;disk drive&quot; </li></ul><ul><li>The providers translate commands like CD and DIR into whatever the underlying store needs to see </li></ul>
    26. 26. Just a few changes <ul><li>PowerShell does have a few quirks when compared to Cmd.exe… </li></ul><ul><ul><li>Cd .. , not Cd.. (needs the space) </li></ul></ul><ul><ul><li>Cd &quot;Program Files&quot; not Cd Program Files (paths with spaces need to be in quotes) </li></ul></ul><ul><ul><li>Etc. </li></ul></ul><ul><li>You usually get used to these minor changes pretty quickly </li></ul>
    27. 27. You've already used cmdlets! <ul><li>Cd, Ls, Dir, Copy, and Cp are all cmdlets (pronounced &quot;command-lets&quot;) </li></ul><ul><li>Technically, these are aliases, or nicknames, to actual cmdlets </li></ul><ul><li>Cmdlets are written in a .NET Framework language </li></ul><ul><li>Cmdlets are bundled into DLL files called snap-ins or PSSnapIns </li></ul>
    28. 28. Aliases <ul><li>Aliases are just &quot;short names&quot; for cmdlets </li></ul><ul><li>They're easier to type </li></ul><ul><li>They provide consistency with old-style command names </li></ul><ul><li>Many aliases come built in, and you can create your own </li></ul>
    29. 29. That's why dir /s doesn't work <ul><li>Dir is an alias for Get-ChildItem </li></ul><ul><li>The alias only covers the cmdlet name – it doesn't change the parameters the cmdlet uses </li></ul><ul><li>Get-ChildItem uses a different parameter to recurse subdirectories </li></ul><ul><li>Dir –recurse or Dir –r will do the trick </li></ul><ul><li>Using an alias is exactly the same as using the cmdlet that the alias 'points' to </li></ul>
    30. 30. Finding cmdlet/alias names <ul><li>You know the alias, and want to find the cmdlet name: Help alias </li></ul><ul><li>You know the cmdlet, and want to find aliases: gal | where { $_.ResolvedCommandName -eq &quot; cmdlet &quot; } </li></ul>
    31. 31. Working with aliases <ul><li>Get all alias: Get-Alias or Gal or Dir Alias: </li></ul><ul><li>Add an alias: New-Alias </li></ul><ul><li>Remove an alias: Remove-Item in the Alias: drive </li></ul>
    32. 32. Working with cmdlets <ul><li>See all cmdlets: Get-Command </li></ul><ul><li>See all &quot;Get&quot; cmdlets: Get-Command –verb Get </li></ul><ul><li>See all &quot;Command&quot; cmdlets: Get-Command –noun Command </li></ul><ul><li>Notice the naming convention? Verb-SingularNoun </li></ul>
    33. 33. Snap-ins <ul><li>Cmdlets are &quot;packaged&quot; in a snap-in </li></ul><ul><li>Multiple snap-ins can be loaded into the shell ( Add-PSSnapIn ), extending its capabilities </li></ul><ul><li>120+ cmdlets provided in the default snapins ( Get-PSSnapin ) </li></ul><ul><li>Just see the cmdlets added by a particular snapin: Get-Command –PSSnapin snapin </li></ul>
    34. 34. Consistency! <ul><li>Cmdlet names might seem long (that's why you have aliases)… but there's a reason! </li></ul><ul><li>Consistent verb-noun naming means you can guess what a cmdlet name would be based on the functionality you want </li></ul><ul><li>This makes learning to use the shell easier </li></ul>
    35. 35. Parameters <ul><li>Like old-style command-line utilities, cmdlets have parameters (or &quot;switches&quot;) </li></ul><ul><li>These customize the behavior of a cmdlet </li></ul><ul><li>Parameter names are preceded by a dash </li></ul><ul><li>A space separates the parameter name and its value </li></ul>
    36. 36. Parameters (con't) <ul><li>Parameters are documented in Help </li></ul><ul><li>Parameter names may seem long… but they're clear… </li></ul><ul><li>… and you only have to type enough to differentiate from other parameter names (e.g., you can be lazy) </li></ul><ul><li>Positional parameters don't need the name at all – just type the values in the correct order </li></ul>
    37. 37. Parameter help
    38. 38. Remember! <ul><li>PowerShell is all about self-discovery </li></ul><ul><li>When you need to do something but don't know the cmdlet name… look it up! </li></ul><ul><li>Help *Service* </li></ul><ul><li>Get-Command -noun whatever </li></ul><ul><li>Get-Command </li></ul><ul><li>Help </li></ul>
    39. 39. Cmdlets: Objects, not text <ul><li>So far the cmdlets you've run have seemed to produce text lists as their output… </li></ul><ul><li>… not so! They actually work with objects </li></ul><ul><li>Object is a generic term that refers to some functional piece of software, like a process, or a service, or an event log </li></ul>
    40. 40. Objects <ul><li>When you run a cmdlet, it generally produces objects as its output </li></ul><ul><li>These objects are actual functioning pieces of Windows </li></ul><ul><li>Get-Service doesn't produce a list of services… it grabs all the actual services which are installed on the computer </li></ul>
    41. 41. Objects <ul><li>Everything in PowerShell is an &quot;object&quot; </li></ul><ul><li>&quot;Object&quot; is just a generic word for &quot;functional thingy&quot; </li></ul><ul><li>Objects have properties which describe them… </li></ul><ul><li>… and methods, which cause them to take some action </li></ul><ul><li>Services, processes, event logs, etc. are all objects </li></ul>
    42. 42. Get-Member <ul><li>Piping an object to Get-Member (gm) tells you about the object </li></ul><ul><ul><li>What type it is (e.g., what kind of object) </li></ul></ul><ul><ul><li>What properties it has </li></ul></ul><ul><ul><li>What methods it has </li></ul></ul><ul><li>Get-Member teaches you about objects by revealing what they are and what they can do for you </li></ul>
    43. 43. Object properties <ul><li>A service has certain properties that describe it: </li></ul><ul><ul><li>Name </li></ul></ul><ul><ul><li>Started (True or False) </li></ul></ul><ul><ul><li>DisplayName </li></ul></ul><ul><ul><li>ServiceType </li></ul></ul><ul><ul><li>Status (Running or Stopped) </li></ul></ul><ul><ul><li>Etc. </li></ul></ul><ul><li>The text list you see consists of some of these properties' values (the ones highlighted here) </li></ul>
    44. 44. The Pipeline <ul><li>All cmdlets run in a pipeline </li></ul><ul><li>At the end of the pipeline is a special cmdlet called Out-Default </li></ul><ul><li>Out-Default takes whatever objects are in the pipeline, and uses some of their properties to construct a text list </li></ul><ul><li>That's why you see text output when you run a cmdlet like Get-Service </li></ul>
    45. 45. A Simple Pipeline Example <ul><li>Property = Value </li></ul><ul><li>Property = Value </li></ul><ul><li>Property = Value </li></ul><ul><li>Property = Value </li></ul>
    46. 46. Piping cmdlets <ul><li>Because nothing is converted to text until the end of the pipeline… </li></ul><ul><li>… you can &quot;pipe&quot; objects from one cmdlet to another </li></ul><ul><li>Each cmdlet can then work directly with the objects' properties </li></ul>
    47. 47. Multi-Cmdlet Pipeline <ul><li>Property = Value </li></ul><ul><li>Property = Value </li></ul><ul><li>Property = Value </li></ul><ul><li>Property = Value </li></ul>
    48. 48. Action Cmdlets <ul><li>Many times, the common things you can &quot;do&quot; with an are available as PowerShell cmdlets </li></ul><ul><li>Stop-Service, Start-Service, Pause-Service, Resume-Service, etc. </li></ul><ul><li>Many of these &quot;action&quot; cmdlets don't output objects at all – so you see no text output when using them </li></ul>
    49. 49. Multi-Cmdlet Pipeline
    50. 50. Object passthrough <ul><li>Cmdlets that &quot;consume&quot; objects (but don't normally output any) often have a –passThru parameter which forces them to pass their objects down the pipeline </li></ul><ul><li>Stop-Service is an example of one of these cmdlets </li></ul>
    51. 51. Multi-Cmdlet Pipeline <ul><li>Property = Value </li></ul><ul><li>Property = Value </li></ul><ul><li>Property = Value </li></ul><ul><li>Property = Value </li></ul>
    52. 52. Remember! <ul><li>You only see text output when there are objects left in the pipeline </li></ul><ul><li>No objects remaining… no output </li></ul><ul><li>Some cmdlets &quot;consume&quot; objects and do something with them, but don't output any objects </li></ul><ul><li>A –passThru parameter forces a cmdlet to pass its objects down the pipeline for further use </li></ul>
    53. 53. Remember! <ul><li>Object have properties </li></ul><ul><li>The cmdlets we're going to look at utilize these properties </li></ul><ul><li>Wonder what properties an object has? Pipe the object to Get-Member to find out </li></ul>
    54. 54. Sorting objects <ul><li>Sorts objects in descending or ascending (default) order, using the property or properties you specify </li></ul><ul><ul><li>Sort-Object Name </li></ul></ul><ul><ul><li>Sort-Object DisplayName -descending </li></ul></ul><ul><li>Pipe objects in to sort them; the sorted objects are piped out </li></ul>
    55. 55. Measuring objects <ul><li>By default, counts the number of objects piped in </li></ul><ul><li>The objects are not piped out – only the measurement results are piped out (meaning your original objects are &quot;lost&quot;) </li></ul>
    56. 56. Selecting object properties <ul><li>Takes piped-in objects and just keeps the properties you specify </li></ul><ul><ul><li>Select-Object Name,DisplayName </li></ul></ul><ul><li>Good for &quot;narrowing down&quot; the properties that show in your output </li></ul><ul><li>The original objects are not piped out (they are &quot;lost&quot;) </li></ul><ul><li>New, custom objects – with just the properties you specify – are piped out </li></ul>
    57. 57. Keeping the first/last object(s) <ul><li>You can also keep just the first &quot;x&quot; or last &quot;x&quot; number of objects </li></ul><ul><ul><li>Select-Object –first 10 </li></ul></ul><ul><ul><li>Select-Object –last 20 </li></ul></ul><ul><li>If you just do this, the original objects are piped out </li></ul>
    58. 58. Exporting objects <ul><li>Objects can be exported to CSV or an XML format </li></ul><ul><ul><li>Export-CSV filename </li></ul></ul><ul><ul><li>Export-CliXML filename </li></ul></ul><ul><li>Useful for generating reports, or persisting objects across sessions </li></ul>
    59. 59. Importing objects <ul><li>Reads in a CSV or XML file and constructs objects from them </li></ul><ul><li>Each line in the CSV, or each XML node, becomes an object with all the properties contained in the file </li></ul><ul><ul><li>Import-CSV filename </li></ul></ul><ul><ul><li>Import-CliXML filename </li></ul></ul>
    60. 60. Secure by Default <ul><li>By default: </li></ul><ul><ul><li>PowerShell won't run scripts </li></ul></ul><ul><ul><li>When configured to run scripts, the shell can require that they be digitally signed </li></ul></ul><ul><ul><li>.PS1 filename extension not associated with the shell </li></ul></ul><ul><ul><li>Must specify a path in order to run a script </li></ul></ul>
    61. 61. SBD: Won't run scripts <ul><li>PowerShell has an ExecutionPolicy which is set to Restricted by default – no scripts will run </li></ul><ul><li>Other ExecutionPolicy settings: </li></ul><ul><ul><li>AllSigned: Only signed scripts run </li></ul></ul><ul><ul><li>RemoteSigned: Local scripts don't need to be signed, remote ones (downloaded) do </li></ul></ul><ul><ul><li>Unrestricted: All scripts will run (bad idea in a production environment) </li></ul></ul>
    62. 62. What is script signing? <ul><li>Signed .PS1 files contain a &quot;signature block&quot; in comments at the end of the file </li></ul><ul><li>Intact signature means… </li></ul><ul><ul><li>The script has not been modified since signed </li></ul></ul><ul><ul><li>The identity of the script author/signer is verified </li></ul></ul>
    63. 63. Script Signing
    64. 64. Controlling ExecutionPolicy <ul><li>Get-ExecutionPolicy and Set-ExecutionPolicy cmdlets </li></ul><ul><li>Download ExecutionPolicy ADM template (for Group Policy) from Microsoft (URL on class CD) </li></ul>
    65. 65. SBD: .PS1 association <ul><li>.PS1 filename extension associated (by default) with Notepad, not the shell </li></ul><ul><li>Double-clicking a script file won't execute it, it'll just open it for editing </li></ul><ul><li>Helps prevent scripts sent via e-mail from being accidentally executed a la VBScript </li></ul>
    66. 66. SBD: Must specify a path <ul><li>Create a script named dir.ps1 </li></ul><ul><li>Try to execute it by running Dir </li></ul><ul><li>You can't: In order to run a script, you must specify a path - ./dir will work </li></ul><ul><li>Helps visually distinguish a script from a built-in command </li></ul>
    67. 67. Alternate Credentials <ul><li>Some PowerShell cmdlets have a -credential parameter which accepts either a username or a PSCredential object that specifies alternate credentials to use </li></ul><ul><li>Get-WMIObject is a good example </li></ul><ul><li>Providing a username launches a graphical dialog where you enter the password </li></ul>
    68. 68. Storing alternate credentials <ul><li>Get-Credential prompts for a credential and securely stores it in a variable </li></ul><ul><li>The variable can then be provided as the value of a –credential parameter </li></ul><ul><li>Lets you create a credential once, and then use it multiple times </li></ul><ul><li>Hint: Put this in your PowerShell profile to have it create the credential each time the shell runs </li></ul>
    69. 69. Sidebar: Profiles <ul><li>A .PS1 file that is automatically executed each time the shell loads </li></ul><ul><li>No profile exists by default </li></ul><ul><li>Create …DocumentsWindowsPowerShell folder, create Microsoft.PowerShell_Profile.PS1 file </li></ul><ul><li>Simply fill the file with commands that you want run each time the shell loads </li></ul>
    70. 70. What is WMI? <ul><li>A system for remotely obtaining management information… </li></ul><ul><li>… and in limited cases, reconfiguring settings </li></ul><ul><li>Implemented as a service since Windows 2000 (and available for NT 4) </li></ul><ul><li>Based in industry-standard techniques developed by the Desktop Management Task Force (DMTF) </li></ul>
    71. 71. WMI structure <ul><li>Namespaces typically align to products (Windows, SQL, IIS, DNS, etc) </li></ul><ul><li>Classes live in namespaces and represent manageable components (disks, users, Web sites, NICs, etc) </li></ul><ul><li>Instances are real-world occurrences of a class (two logical disks = two instances of the disk class) </li></ul>
    72. 72. Classes & instances <ul><li>Instances are objects, meaning they have properties </li></ul><ul><li>They can also have methods, which are the things you can do with an object (e.g., Disk objects have a Defrag method) </li></ul><ul><li>Review properties to see management information; execute methods to make configuration changes </li></ul>
    73. 73. WMI query options <ul><li>Get all properties for instances of a given class </li></ul><ul><li>Get all objects that match a WMI Query Language (WQL) query </li></ul><ul><li>In both cases, the Get-WMIObject cmdlet does the work </li></ul>
    74. 74. Simple WMI <ul><li>Get-WMIObject classname [-computerName computername ] [-credential PSCredential ] </li></ul><ul><li>Retrieves all instances of the designated class (optionally, from the specified computer using the specified credentials) </li></ul>
    75. 75. WMI Classes <ul><li>Where can you get a list of classes? </li></ul><ul><li>For the core rootcimv2 namespace… </li></ul><ul><ul><li>Use the WMI Documentation </li></ul></ul><ul><ul><li>Ask PowerShell for a list of classes </li></ul></ul><ul><ul><li>Use the WMI Explorer (, click “Free Tools”) </li></ul></ul>
    76. 76. WQL Queries <ul><li>SQL-like syntax </li></ul><ul><li>Specify the properties you want… </li></ul><ul><li>… the class you're querying… </li></ul><ul><li>… and the criteria (to filter out instances you don't want) </li></ul>
    77. 77. WQL Example <ul><li>SELECT { * | Property,Property } FROM { Class } [ WHERE Property = Value ] </li></ul><ul><li>SELECT * FROM Win32_LogicalDisk WHERE DriveType = 3 </li></ul>
    78. 78. Testing WQL Queries <ul><li>Use the built-in Wbemtest.exe GUI tool </li></ul><ul><ul><li>Connect to a namespace (rootcimv2 is the default namespace used by PowerShell) </li></ul></ul><ul><ul><li>Enter a WQL query </li></ul></ul><ul><ul><li>See the objects that come back </li></ul></ul><ul><li>Great way to prototype, test, and refine queries in a graphical environment </li></ul>
    79. 79. WQL Queries in PowerShell <ul><li>Get-WMIObject –query &quot; WQL query &quot; </li></ul><ul><li>Gwmi –qu &quot;SELECT * FROM Win32_LogicalDisk WHERE DriveType = 3&quot; </li></ul>
    80. 80. WMI and the pipeline <ul><li>Get-WMIObject returns objects with properties … </li></ul><ul><li>… pipe them to Get-Member to see those properties… </li></ul><ul><li>… or use the objects in the pipeline with Sort, Select, Group, and the other cmdlets you've learned </li></ul>
    81. 81. Comparisons <ul><li>The purpose of a comparison is to generate a True or False result </li></ul><ul><li>PowerShell provides the $True and $False variables to represent these Boolean values </li></ul><ul><li>All comparisons result in either $True or $False </li></ul>
    82. 82. Comparison operators <ul><li>-eq Equality </li></ul><ul><li>-ne Inequality </li></ul><ul><li>-gt Greater than </li></ul><ul><li>-lt Less than </li></ul><ul><li>-ge Greater than or equal to </li></ul><ul><li>-le Less than or equal to </li></ul>
    83. 83. Comparison examples <ul><li>Supposing $_ represents a process… </li></ul><ul><ul><li>$_.Handles –gt 1000 </li></ul></ul><ul><ul><li>$_.Name –eq &quot;Notepad&quot; </li></ul></ul><ul><ul><li>$_.Responding Note that the Responding property is either True or False; it does not have to be compared to $True or $False to generate a True/False result </li></ul></ul>
    84. 84. Filtering in the pipeline <ul><li>Where-Object accepts a collection of objects and examines each one </li></ul><ul><li>Only those objects meeting the criteria you specify are passed down the pipeline </li></ul><ul><li>In your comparison expression, $_ represents &quot;the current pipeline object we're examining.&quot; </li></ul>
    85. 85. Where-Object <ul><li>Get-Service | Where-Object { $_.Status –eq &quot;Running&quot; } | Sort-Object Name -descending </li></ul>
    86. 86. Complex comparisons <ul><li>Need to compare more than one condition in a single expression? </li></ul><ul><ul><li>-and returns True if both are True </li></ul></ul><ul><ul><li>-or returns True if either is True </li></ul></ul><ul><ul><li>-not reverse True/False </li></ul></ul>
    87. 87. Complex example <ul><li>Supposing $_ represents a WMI Win32_Service instance… </li></ul><ul><li>$_.StartMode –eq &quot;Auto&quot; </li></ul><ul><li>-and </li></ul><ul><li>$_.State –ne &quot;Running&quot; </li></ul>
    88. 88. Formatting output <ul><li>We've talked before about how the pipeline ends in Out-Default, which turns objects into text </li></ul><ul><li>The actual process is somewhat more complicated than that! </li></ul><ul><li>Out-Default actually redirects objects to Out-Host, which does the work of displaying objects </li></ul>
    89. 89. Out-Host <ul><li>Out-Host can't display normal objects… </li></ul><ul><li>… it can only display special PowerShell formatting objects </li></ul><ul><li>So when Out-Host receives normal objects, it calls on PowerShell's formatting system to turn them into formatting objects </li></ul>
    90. 90. Formatting rule #1 <ul><li>Does the object type have a view defined in one of the .format.ps1xml files? </li></ul><ul><ul><li>If yes… use that view, which specifies either table, list, or wide layout. </li></ul></ul><ul><ul><li>If not… go to rule 2. </li></ul></ul>
    91. 91. Formatting rule #2 <ul><li>Does this type of object have a set of Default Display Properties define in a .ps1xml file? </li></ul><ul><ul><li>If Yes, use only the default properties for the next decision </li></ul></ul><ul><ul><li>If No, use all of the object's properties for the next decision </li></ul></ul>
    92. 92. Formatting rule #3 <ul><li>Are we displaying >=5 properties? </li></ul><ul><ul><li>If Yes, choose a List layout </li></ul></ul><ul><ul><li>If No, choose a Table layout </li></ul></ul>
    93. 93. Formatting rule #4 <ul><li>Using the properties we've chosen, and using the layout we've chosen, call a formatting cmdlet to create the formatting objects </li></ul><ul><ul><li>Format-Table (ft) </li></ul></ul><ul><ul><li>Format-Wide (fw) </li></ul></ul><ul><ul><li>Format-List (fl) </li></ul></ul>
    94. 94. Formatting process Get-Service Out-Default Out-Host Format-Table
    95. 95. That's just the default… <ul><li>You can pipe objects to any of the Format-* cmdlets on your own </li></ul><ul><li>This lets you specify the layout you want </li></ul><ul><li>Use the Format-* cmdlets to specify the properties you want displayed, too </li></ul><ul><li>Produces formatting objects (meaning the Format-* cmdlet has to be the last thing in the pipeline) </li></ul>
    96. 96. Let ’s Play <ul><li>Let ’s see what we can do with FT and FL… </li></ul><ul><ul><li>Select properties to display in the output </li></ul></ul><ul><ul><li>Control table sizing </li></ul></ul><ul><ul><li>Grouping the output by a selected property (sort the objects first!) </li></ul></ul>
    97. 97. Input and output <ul><li>Read-Host and Write-Host read and write input directly from the console </li></ul><ul><li>Write-Output writes output to the Success pipeline </li></ul><ul><ul><li>Anything in the pipeline can potentially end up displayed in the console </li></ul></ul><ul><li>At the end of the pipeline is Out-Default. </li></ul>
    98. 98. Write-Host vs. Write-Output Write-Output Out-Default Write-Host Out-Host Where-Object
    99. 99. Fun Trick <ul><li>Try piping output (say, of Get-Service) to ConvertTo-HTML </li></ul><ul><li>Try piping that output to Out-File and specifying a file name </li></ul><ul><li>Neat, huh? </li></ul>
    100. 100. Variables <ul><li>PowerShell uses variables as temporary, named storage for objects </li></ul><ul><li>Variable names begin with $ </li></ul><ul><li>Names can contain (mainly) letters, numbers, and underscores </li></ul><ul><li>Variables are not automatically persisted by the shell </li></ul>
    101. 101. Variable FAQ <ul><li>How long can variable names be? Long enough. </li></ul><ul><li>Can I declare them in advance? Yes, using New-Variable </li></ul><ul><li>Do I have to declare them in advance? No, and there's no way to force yourself. </li></ul><ul><li>Are all variables the same &quot;type?&quot; No, they are the &quot;type&quot; of whatever object they contain… </li></ul>
    102. 102. Variables are objects <ul><li>Variables are really just names for an area in memory where objects are stored </li></ul><ul><li>Variables aren't things themselves; they're just containers for actual objects </li></ul><ul><li>A variable exposes the properties and methods of the object(s) it contains </li></ul><ul><li>Pipe a variable to Get-Member to see what it can do! </li></ul>
    103. 103. Variable types <ul><li>PowerShell automatically tries to figure out what &quot;type&quot; a variable is when you create it and when you use it </li></ul><ul><li>This allows &quot;5&quot; to be treated as a number when appropriate, and as a text string when appropriate… </li></ul><ul><li>… although sometimes PowerShell gets confused about which type it should be using </li></ul>
    104. 104. Common types <ul><li>[string] </li></ul><ul><li>[int] </li></ul><ul><li>[boolean] </li></ul><ul><li>[regex] </li></ul><ul><li>[single] </li></ul><ul><li>[double] </li></ul><ul><li>[array] </li></ul><ul><li>[adsi] </li></ul><ul><li>[wmi] </li></ul><ul><li>[hashtable] </li></ul><ul><li>[xml] </li></ul><ul><li>[char] </li></ul><ul><li>Lots more! </li></ul>
    105. 105. Arrays <ul><li>A special kind of variable capable of holding multiple objects… </li></ul><ul><li>… usually of the same type, but not necessarily </li></ul><ul><li>Each object in the array has an index , which is its location within the array </li></ul><ul><li>0 is the bottom index (the first item) </li></ul><ul><li>The special index -1 always returns the last item in the array </li></ul>
    106. 106. Creating an array <ul><li>Any cmdlet which returns a collection of objects is returning an array – and that collection can be stored in a single variable </li></ul><ul><li>You can also create your own arrays $arr = @( 1,2,3,4,5 ) </li></ul><ul><li>PowerShell always treats any comma-separated list as an array – remember this!!! </li></ul>
    107. 107. Using an array <ul><li>You can pipe arrays to cmdlets – just like you can pipe any collection of objects to most cmdlets </li></ul><ul><li>Access individual elements in the array by specifying an [index] in square brackets: $arr[0] </li></ul>
    108. 108. Array tip: <ul><li>Arrays and collections aren't technically the same thing, but for most purposes you can think of them as the same thing </li></ul><ul><li>Collection of objects = Array of objects </li></ul>
    109. 109. Escape characters <ul><li>` (backtick) is the universal escape character in PowerShell </li></ul><ul><li>` at the end of a line &quot;escapes&quot; the carriage return (e.g., line continuation) </li></ul><ul><li>` before a space &quot;escapes&quot; it (e.g., makes it a literal space) </li></ul><ul><li>` before certain characters performs special functions </li></ul>
    110. 110. Inventorying Information <ul><li>Let ’s use WMI to inventory information </li></ul><ul><li>The neat bit is that a single command can pull info from multiple computers </li></ul><ul><li>How will we know which computer each bit came back from? </li></ul><ul><li>We ’ll look at technique that uses no scripting! </li></ul><ul><li>We ’ll be using Service Pack info </li></ul>
    111. 111. Scripting <ul><li>Scripting in PowerShell is really just pasting commands into a text file </li></ul><ul><li>There are a few “scripting constructs” you can use to implement logic and flow control for more complex processes </li></ul><ul><li>Scripts are just text files with a .PS1 filename extension </li></ul><ul><li>You can edit with Notepad, although a PowerShell-specific editor is far better </li></ul>
    112. 112. Foreach <ul><li>Used to take a collection of objects and go through them, one at a time </li></ul><ul><li>Lets you perform multiple operations per object </li></ul><ul><li>Let ’s modify our WMI inventory command to work in this fashion </li></ul>
    113. 113. Customizing objects <ul><li>Pipe an object to Add-Member to add a NoteProperty , which contains a static value </li></ul><ul><li>$obj | Add-Member NoteProperty PropertyName PropertyValue </li></ul><ul><li>Use Write-Output to output the new object </li></ul><ul><li>Let ’s use this to add a “ComputerName” property to our WMI object </li></ul>
    114. 114. Switch <ul><li>Used to compare a variable or property value to a range of possible values, and take some action </li></ul><ul><li>We ’ll use this to translate the build number into a more readable OS WinVersion property </li></ul>
    115. 115. Multiple Sources? <ul><li>What if we also wanted our output to include a BIOS serial number / call tag property? </li></ul><ul><li>We could query Win32_BIOS… how do we combine it with our existing output? </li></ul><ul><li>Ideally, our output should be a SINGLE object that has properties for the COMBINED information… </li></ul>
    116. 116. Create a Custom Object <ul><li>We ’ll use New-Object PSObject to create a new, blank object </li></ul><ul><li>We ’ll use Add-Member to add the information we want – from various sources </li></ul><ul><li>We ’ll output the combined object </li></ul>
    117. 117. Making it a Tool <ul><li>Let ’s wrap the whole thing in a parameterized function that accepts an input filename </li></ul><ul><li>We ’ll expect the input file to contain one computer name per line </li></ul>
    118. 118. Making it a Pipeline Tool <ul><li>Instead of specifying a filename, let ’s modify the function to accept a collection of computer names from the pipeline as its input </li></ul><ul><li>This lets us use a variety of input sources, so long as they generate a collection of computer names – doesn ’t need to be a file (maybe from AD?) </li></ul>
    119. 119. Output Flexibility <ul><li>By accepting pipeline input, we add flexibility </li></ul><ul><li>By producing pipeline output , we add lots of flexibility! </li></ul><ul><li>Let ’s see </li></ul>
    120. 120. Managing AD <ul><li>Let ’s look at how to import users from a CSV file and make them into AD user accounts </li></ul><ul><li>We ’ll use the Import-CSV and New-DUser cmdlets </li></ul><ul><li>We ’ll allow the CSV file to contain arbitrary headings (not AD attribute names) </li></ul>
    121. 121. Thank You! <ul><li>Please feel free to pick up a card if you ’d like copies of my session materials </li></ul><ul><li>I ’ll be happy to take any last questions while I pack up </li></ul><ul><li>Please complete and submit an evaluation form for this and every session you attend! </li></ul>
    122. 123. This slide deck was used in one of our many conference presentations. We hope you enjoy it, and invite you to use it within your own organization however you like. For more information on our company, including information on private classes and upcoming conference appearances, please visit our Web site, . For links to newly-posted decks, follow us on Twitter: @concentrateddon or @concentratdgreg This work is copyright ©Concentrated Technology, LLC