Monad The New Microsoft Command Shell - PowerPoint PPT Presentation

1 / 30
About This Presentation
Title:

Monad The New Microsoft Command Shell

Description:

Mode LastWriteTime Length Name -a--- 8/29/2002 5:00 AM 734 hosts. Modify fields displayed ... MSH ls hosts | sort-object Length. Sort by modification time? ... – PowerPoint PPT presentation

Number of Views:68
Avg rating:3.0/5.0
Slides: 31
Provided by: peterp63
Category:

less

Transcript and Presenter's Notes

Title: Monad The New Microsoft Command Shell


1
MonadThe New Microsoft Command Shell
  • Peter Provost
  • peter.provost_at_microsoft.com
  • http//www.peterprovost.org/

2
Unix Shell Example
  • List a file in a directory with details
  • ls l hosts
  • -rw-rr--  1 root root 41 Mar 18  2005 hosts
  • Modify fields displayed
  • ls go hosts
  • -rw-rr--  1  41 Mar 18  2005 hosts
  • Extract size and filename
  • ls l hosts cut c 24-27,41-
  • 41 hosts

3
Unix Shell Example (continued)
  • Show access time?
  • ls lu
  • Sort by size?
  • ls lS
  • Sort by modification time?
  • ls -lt

4
Monad Example
  • List a file in a directory with details
  • MSHgt ls hosts
  • Mode LastWriteTime Length Name
  • ---- ------------- ------ ----
  • -a--- 8/29/2002 500 AM 734
    hosts
  • Modify fields displayed
  • MSHgt ls hosts format-table LastWriteTime,Name
  • LastWriteTime Name
  • ------------- ----
  • 8/29/2002 50000 AM hosts
  • Extract size and filename
  • MSHgt ls l hosts format-table Length,Name
  • Length Name
  • ------ ----
  • 734 hosts

5
Monad Example (continued)
  • Show access time?
  • MSHgt ls hosts format-table Name,LastAccessTime
  • Sort by size?
  • MSHgt ls hosts sort-object Length
  • Sort by modification time?
  • MSHgt ls hosts sort-object LastWriteTime

6
More Monad Examples!
  • Show files modified in last 7 days
  • MSHgt ls where-object _.LastWriteTime ge
  • System.DateTimeNow.AddDays(-7)
  • Show processes using 500 handles, sorted by Id
  • MSHgt ps where-object _.HandleCount ge 500
  • sort-object Id
  • Show signer of each process binary
  • MSHgt ps foreach-object
  • p _.MainModule.FileName
  • sig get-authenticodesignature p
  • echo (p " sig.SignerCertificate.Issue
    r)

7
Monad is a New Shell
  • Similar to Unix shells, but
  • Pipelines of .Net objects
  • Object properties/methods directly accessible and
    discoverable
  • COM, WMI, XML, etc. accessed with same semantics
  • User-controlled formatting of objects
  • Standardized command parameter processing
  • Rich scripting language
  • Providers extend the navigation namespace

8
Commands
  • Verb-Noun
  • MSHgt verb-noun param1 value1
  • param2 value2a,value2b param3value3
  • You can alias
  • MSHgt set-alias gps get-process
  • ls and dir are aliases for get-childitem
  • ps is alias for get-process
  • Parameters can be positional
  • MSHgt get-process processname lsass
  • MSHgt get-process lsass
  • Many parameters can be wildcarded
  • MSHgt get-process c
  • Partial parameter names allowed
  • MSHgt get-process -p lsass

9
Commands Emit Objects
  • Traditional text parsing replaced with direct
    object manipulation
  • A default text view of objects is dynamically
    computed
  • Table for objects with lt 5 properties
  • List for objects with 5 or more properties
  • Get-Member tells you about the objects
  • MSHgt get-process get-member

10
Finding Information
  • Finding Commands
  • MSHgt get-command i
  • MSHgt get-command verb process
  • MSHgt get-command type Alias Function
  • Filter Cmdlet ExternalScript
  • Application Script All
  • Man-page style help on language and commands
  • MSHgt get-help
  • MSHgt get-help ltcommandgt
  • MSHgt ltcommandgt -?
  • MSHgt get-help about_while
  • MSHgt get-help where _.Synopsis -match
    "process"

11
Object Manipulation
  • Objects can be pipelined to other functions
  • Related commands
  • MSHgt get-process notep stop-process
  • Object utilities
  • MSHgt get-process where _.Handles ge 500
    group-object Company sort-object Count
  • Your functions
  • Direct object manipulation
  • MSHgt np get-process notepad
  • MSHgt np.Workingset / 1024
  • MSHgt np.WaitForExit()

12
Ubiquitous Parameters
  • -Debug
  • Programmer-level information
  • -ErrorAction SilentlyContinue Stop Continue
    Inquire
  • What to do if an error occurs?
  • -ErrorVariable VariableName
  • Assign errors to a variable
  • -OutputVariable VariableName
  • Output assigned to a variable
  • -Verbose
  • Additional information about the activities being
    performed

13
Trusting Operations
  • Commands with side-effects support
  • -Whatif
  • MSHgt get-process
  • where-object _.Handles ge 500
  • stop-process whatif
  • -Confirm
  • MSHgt stop-process pr s -confirm
  • Can also use -Verbose
  • MSHgt stop-process pr a-xqr-t -verbose

14
Extending the Namespace
  • Providers allow namespace navigation to go beyond
    the filesystem
  • Monad includes a default set
  • FileSystem, Registry, Certificate, Alias,
    Environment, Function, Variable
  • You can write your own
  • Navigation commands work
  • MSHgt cd Registry\
  • MSHgt dir YourProvider\foo

15
Finding Data
  • Data stores surfaced as drives in providers
  • MSHgt get-drive
  • MSHgt dir HKLM\SOFTWARE\Microsoft
  • Drive is a namespace with numerous pieces of
    information
  • Item, ChildItem, Content, Property, ACL, etc.
  • New navigation/interaction model supported with
    aliases for existing commands

16
Namespace Functions
  • Mounting new drives with names
  • MSHgt new-drive -name SRC -provider FileSystem
    -root c\development\cab\main -description
    CAB source code
  • MSHgt cd SRC\parser
  • Great wildcarding
  • MSHgt dir a-ftc
  • MSHgt dir T?.msh
  • Rich common semantics
  • MSHgt dir \logs include .txt exclude A
    -recurse -force
  • Drive specific extensions
  • MSHgt dir cert -recurse codesigning
  • Tab-Completion in all Drives
  • MSHgt dir HKLM\SoltTABgt\MiltTABgt gt
    HLKM\Software\Microsoft

17
Scripting
  • A script is executed the same as if the commands
    were typed interactively
  • Supports scripting .NET objects
  • Loose, strong, and extensible typing models
  • Uniform syntax for wide range of types
  • WMI, XML, COM, ADSI, ADO
  • Rich variable semantics (typed, read-only,
    constraints, descriptions)
  • Rich operators and control structures (C-like
    with access to commands utilities)
  • Functions (positional, named, typed, constrained
    params)

18
Scripting .NET
  • Creating .Net objects
  • MSHgt dNew-Object System.DateTime 2005,4,20
  • MSHgt DateTime"4-20-2005"
  • Will try Parse() method, Constructor, Converter
  • Inspecting properties and methods
  • MSHgt DateTime"4-20-2005" get-member
  • MSHgt DateTime get-member -static
  • Accessing properties-methods
  • Instance
  • MSHgt d.DayOfWeek
  • MSHgt d.AddMonths(6)
  • Static
  • MSHgt DateTimeNow
  • MSHgt DateTimeIsLeapYear(2005)

19
Typing
  • Loose
  • MSHgt d"4/20/2005
  • MSHgt Function foo() args0
  • Strong
  • MSHgt datetimed4/20/2005
  • MSHgt function foo(datetimedate) date
  • MSHgt int char a
  • Extensible
  • Can extend types via MSHHOME\types.mshxml
  • See .NET DateTime class DateTime property
  • MSH works on any .NET type - not a fixed set of
    scripting types

20
Typing Examples
  • MSHgt char a
  • MSHgt int char a
  • MSHgt char (intchar"a" - 32)
  • MSHgt w get-wmiobject win32_bios
  • MSHgt w.Version
  • MSHgt (dir)0.mshPath

21
Text Processing Model
  • .NET String class is the foundation
  • Contains(), EndsWith(), Equals(), IndexOf(),
    Insert(), Join(), LastIndexOf(), Length,
    PadLeft(), PadRight(), Remove(), Replace(),
    Split(), StartsWith(), Substring(), ToLower(),
    ToUpper(), Trim(), TrimEnd(), TrimStart()
  • Native support for useful datatypes
  • Regular expressions, XML, arrays, hash tables
  • Rich string operators
  • , , -replace, -match, -like, -eq, -ne, gt, -ge,
    -lt, -le
  • Implicit/explicit casting and coercion
  • Rich utilities
  • match-string, foreach, group, select, sort, where

22
Leveraging .Net classes
  • Script to rotate every image in a directory
  • System.Reflection.Assembly
  • LoadWithPartialName("System.Drawing")
    out-null
  • foreach (f in resolve-path )
  • trap OutOfMemoryException
  • write-host "Error processing" f
    continue
  • img System.Drawing.ImageFromFile(f)
  • format img.RawFormat
  • img.RotateFlip("Rotate90FlipNone")
  • fi get-childitem f
  • newname combine-path (fi.DirectoryName)
    ("rot." fi.Name)
  • img.Save(newname,format)

23
Uniform Data Access Syntax
  • Provides a common user interface to objects of
    different typesystems
  • XML
  • MSHgt x xml"ltagtltbgtltcgtTESTlt/cgtlt/bgtlt/agt"
  • MSHgt x.a.b.c
  • MSHgt wc new-object System.Net.WebClient
  • MSHgt rssdata xmlwc.DownloadString
  • ("http//slashdot.org/index.rss"
    )
  • MSHgt if (rssdata.rss.version eq "2.0")
    echo rssdata.rss.channel.title

24
COM Automation (Internet Explorer)
  • Bind to Internet Explorer COM object
  • MSHgt ie new-object com
    InternetExplorer.Application
  • Reflect against properties/methods
  • MSHgt ie get-member
  • Display properties
  • MSHgt ie.Visible
  • Invoke methods/set properties
  • MSHgt ie.Navigate2("www.uiuc.edu")
  • MSHgt ie.Visible true
  • MSHgt ie.StatusText "Hello World"

25
COM Automation (Word)
  • Bind to Word COM Object
  • MSHgt word new-object com Word.Application
  • Use in pipelines
  • MSHgt word.RecentFiles sort name
    format-table name,index,path auto
  • Access document properties
  • MSHgt doc word.Documents.Open("c\foo.doc")
  • MSHgt doc.characters.count
  • MSHgt doc.sentences.count

26
COM Automation (WScript)
  • Bind to WScript object
  • MSHgt ws new-object -com Wscript.Shell
  • Display popup
  • MSHgt ws.popup("This is a popup",100,"Title",64)
  • Last parameter is a button/icon bit mask
  • 0 OK
  • 1 OK and Cancel
  • 2 Abort, Retry, and Ignore
  • 3 Yes, No, and Cancel
  • 4 Yes and No
  • 5 Retry and Cancel
  • Access other shell functionality
  • MSHgt ws get-member
  • CreateShortcut(), LogEvent(), etc.

16 Stop Mark 32 Question Mark 48 Exclamation
Mark 64 Information Marl
27
Writing Cmdlets
  • .Net class, inherits from Cmdlet
  • Declare parameters as class members
  • Override methods BeginProcessing(),
    ProcessRecord(), EndProcessing()
  • Monad provides
  • Parameter parsing/binding
  • Ubiquitous parameters
  • -Confirm/-Whatif (if you call ShouldProcess())
  • Access to session state
  • Invoke other cmdlets, providers, and host API

28
Cmdlet Example (C)
  • 1 Cmdlet("stop", "ps", SupportsShouldProcesstrue
    )
  • 2 public class StopPs Cmdlet
  • 3
  • 4 Parameter(Mandatorytrue)
  • 5 public string Name
  • 6 protected override void ProcessRecord()
  • 7 Process ps Process.GetProcessesByName(N
    ame)
  • 8 foreach (Process p in ps)
  • 9 if (ShouldProcess(p.ProcessName "ID "
    p.Id))
  • 10
  • 11 p.Kill()
  • 12
  • 13
  • 14
  • 15

29
Get Monad!
  • Monad Shell Beta 2 available from Microsoft
    Download Center
  • Search for Monad
  • Supported on x86 and x64 platforms
  • Documentation Pack also available
  • Requires .Net 2.0 Beta 2 (also available from
    Download Center)

30
Shameless Plug
  • patterns practices is hiring
  • See me after the talk or e-mailDarrel Snow
    dsnow_at_microsoft.com
Write a Comment
User Comments (0)
About PowerShow.com