36
Monad Shell – Task- Monad Shell – Task- Oriented Automation Oriented Automation Framework Framework Jeffrey P. Snover Jeffrey P. Snover Management Architect Management Architect Windows Enterprise Management Windows Enterprise Management Division Division Jsnover Jsnover @ microsoft.com @ microsoft.com

Monad Shell – Task-Oriented Automation Framework

  • Upload
    fauve

  • View
    65

  • Download
    0

Embed Size (px)

DESCRIPTION

Monad Shell – Task-Oriented Automation Framework. Jeffrey P. Snover Management Architect Windows Enterprise Management Division Jsnover @ microsoft.com. Task-Based Administrative Experience. Tasks are the actions users perform from a GUI console Command line Example tasks - PowerPoint PPT Presentation

Citation preview

Page 1: Monad Shell – Task-Oriented Automation Framework

Monad Shell – Task-Oriented Monad Shell – Task-Oriented Automation FrameworkAutomation FrameworkJeffrey P. SnoverJeffrey P. SnoverManagement ArchitectManagement ArchitectWindows Enterprise Management DivisionWindows Enterprise Management DivisionJsnoverJsnover @ microsoft.com @ microsoft.com

Page 2: Monad Shell – Task-Oriented Automation Framework

22

Task-Based Administrative Task-Based Administrative ExperienceExperience Tasks are the actions users perform from aTasks are the actions users perform from a

GUI consoleGUI console Command lineCommand line

Example tasksExample tasks Add user, add disk, remove user, …Add user, add disk, remove user, …

Tasks can be comprised of sub-tasks (e.g., add user)Tasks can be comprised of sub-tasks (e.g., add user) Create account in Active DirectoryCreate account in Active Directory Add account to appropriate GroupsAdd account to appropriate Groups Create a home directoryCreate a home directory ……

Administrative Experience is determined by how tasks are Administrative Experience is determined by how tasks are defined, organized, and exposed to end usersdefined, organized, and exposed to end users

Page 3: Monad Shell – Task-Oriented Automation Framework

33

Microsoft Shell (MSH) MissionMicrosoft Shell (MSH) Mission

Deliver an extensible scripting environment that is secure, Deliver an extensible scripting environment that is secure, interactive, programmable, and production-ready to interactive, programmable, and production-ready to enable consistent and reliable automation of enable consistent and reliable automation of administrative tasks administrative tasks Improve the developer experience by making it easier to add Improve the developer experience by making it easier to add

command-line management capabilities using .NET command-line management capabilities using .NET Improve the administrative experience by enabling IT Pros to Improve the administrative experience by enabling IT Pros to

write secure automation scripts that can run locally or remotelywrite secure automation scripts that can run locally or remotely

DeliverablesDeliverables A scripting language A scripting language An interactive shellAn interactive shell A way to produce task-oriented commandsA way to produce task-oriented commands A set of domain-independent utility commandsA set of domain-independent utility commands A mechanism to do remote scriptingA mechanism to do remote scripting

Page 4: Monad Shell – Task-Oriented Automation Framework

44

MSH Problem StatementMSH Problem Statement Windows administration has not met the needs of administratorsWindows administration has not met the needs of administrators

Overemphasis on GUI-based tools and developer-oriented SDKs Overemphasis on GUI-based tools and developer-oriented SDKs Weak command shell with incomplete coverage and limited automationWeak command shell with incomplete coverage and limited automation

Unix employs a powerful model for automating administration tasksUnix employs a powerful model for automating administration tasks Composition (A | B | C)Composition (A | B | C) Text-based pipelinesText-based pipelines

Command A output processed by command B…Command A output processed by command B… Uniform remoting of commandsUniform remoting of commands

.NET enables Windows to do better than Unix.NET enables Windows to do better than Unix Object-based pipelinesObject-based pipelines Managed codeManaged code

Commands are classesCommands are classes Reflection-based utilitiesReflection-based utilities

Page 5: Monad Shell – Task-Oriented Automation Framework

55

MSH – Key Admin ScenariosMSH – Key Admin Scenarios Better than Unix ShellBetter than Unix Shell

.NET-based experience.NET-based experience Compatibility and InteroperabilityCompatibility and Interoperability

Existing commands and scripts Existing commands and scripts (.exe, .bat, .vbs, …) work(.exe, .bat, .vbs, …) work

Secure Remote ScriptingSecure Remote Scripting Signed cmdlets (tiny commands) Signed cmdlets (tiny commands)

and scriptsand scripts Configuration Settings Configuration Settings

ManagementManagement Get and set configuration values Get and set configuration values

for desktop (network, print, for desktop (network, print, Internet Explorer, …)Internet Explorer, …)

Server role deployment and Server role deployment and operationsoperations

BatchingBatching Execute admin tasks on 1:many Execute admin tasks on 1:many

computerscomputers Seamless navigationSeamless navigation

File system, Registry, AD, WMIFile system, Registry, AD, WMI

Server Systems Administrator - Server Systems Administrator - Sam WatsonSam Watson

Upper MORG ITUpper MORG IT

Enterprise ITEnterprise IT

Windows Server Administrator – Windows Server Administrator – Al YoungAl Young

Enterprise Systems Enterprise Systems Administrator – Ray ClarkAdministrator – Ray Clark

Print Administrator – Lyle Print Administrator – Lyle KramerKramer

Network Systems Administrator – Network Systems Administrator – Chuck ThomasChuck Thomas

Enterprise Security Enterprise Security Administrator – Kevin ParrishAdministrator – Kevin Parrish

Enterprise Network Enterprise Network Administrator – Carlos GarciaAdministrator – Carlos Garcia

User Account Manager – Chad User Account Manager – Chad RiceRice

Core MORG Operations Core MORG Operations Engineer – Engineer – Chris GreenChris Green

Do It Yourselfer – Do It Yourselfer – Frank MartinezFrank Martinez

Core MORG ITCore MORG IT

SORG ITSORG IT

Page 6: Monad Shell – Task-Oriented Automation Framework

66

MSH DemoMSH Demo

Let’s get MSH in focusLet’s get MSH in focus AsAs interactive interactive and and composablecomposable as KSH as KSH

or BASHor BASH As As programmableprogrammable as PERL or RUBY as PERL or RUBY As As production-orientedproduction-oriented as VMS DCL or as VMS DCL or

AS400 CLAS400 CL Makes accessing mgmt information as Makes accessing mgmt information as easyeasy

as accessing a file systemas accessing a file system

Page 7: Monad Shell – Task-Oriented Automation Framework

77

MSH ArchitectureMSH Architecture Monad shell (msh.exe)Monad shell (msh.exe)

Character-based command-line host for Character-based command-line host for the Monad enginethe Monad engine

Monad engine (msh.dll)Monad engine (msh.dll) Script/ParserScript/Parser – processes language – processes language

constructs such as scripts, predicates, constructs such as scripts, predicates, conditionals, etc.conditionals, etc.

Pipeline ProcessorPipeline Processor – manages inter- – manages inter-cmdlet communication via pipescmdlet communication via pipes

Command ProcessorCommand Processor – manages cmdlet – manages cmdlet execution, registration and associated execution, registration and associated metadatametadata

Session StateSession State – manages the data set – manages the data set used by a cmdlet for executionused by a cmdlet for execution

Extended Type SystemExtended Type System – provides a – provides a common interface for accessing common interface for accessing properties, methods, etc. independent of properties, methods, etc. independent of the underlying object typethe underlying object type

Error and Event HandlerError and Event Handler – manages – manages exception to error mapping and reportingexception to error mapping and reporting

Monad ShellMonad Shell

Script & Command ParserScript & Command Parser

Pipeline ProcessorPipeline Processor

SessionSessionStateState

Error &Error &EventEvent

HandlerHandler

ExtendedExtendedTypeType

SystemSystem

Command ProcessorCommand Processor

Hosting Interfaces

Monad EngineMonad Engine

Other HostsOther Hosts

Remoting (WMX)Remoting (WMX)

Page 8: Monad Shell – Task-Oriented Automation Framework

88

Key MSH Concepts For The Key MSH Concepts For The DeveloperDeveloper Cmdlets are .NET classesCmdlets are .NET classes

Think DLLs not EXEsThink DLLs not EXEs

Providers enable groups or families of related cmdlets Providers enable groups or families of related cmdlets (i.e., namespaces)(i.e., namespaces) File System, Registry, Active Directory, …File System, Registry, Active Directory, …

Pipelines are composed of classes (cmdlets) passing Pipelines are composed of classes (cmdlets) passing structured objectsstructured objects Objects are processed into recordsObjects are processed into records

Extended Type System (ETS) simplifies developer Extended Type System (ETS) simplifies developer experienceexperience Common interfaces for operating on pipeline objects independent Common interfaces for operating on pipeline objects independent

of typeof type

Page 9: Monad Shell – Task-Oriented Automation Framework

99

Cmdlet ClassCmdlet Class Cmdlet class properties and methods allow cmdlets toCmdlet class properties and methods allow cmdlets to

Access parameters Access parameters Write objects to output streamsWrite objects to output streams Write errorsWrite errors Access session stateAccess session state … …

CmdletDeclarationAttribute metadata enables MSH to identify .NET CmdletDeclarationAttribute metadata enables MSH to identify .NET class as a cmdletclass as a cmdlet Requires two parameters: VerbName, NounNameRequires two parameters: VerbName, NounName

using System.Management.Automation;using System.Management.Automation;[CmdletDeclarationAttribute("get", [CmdletDeclarationAttribute("get", “process")]“process")]class GetProcess : Cmdletclass GetProcess : Cmdlet{{implementationimplementation}}

Page 10: Monad Shell – Task-Oriented Automation Framework

1010

Writing A cmdletWriting A cmdlet

Cmdlet class defines three virtual methodsCmdlet class defines three virtual methods StartProcessing()StartProcessing() ProcessRecord()ProcessRecord() EndProcessing()EndProcessing()

Cmdlets override one or more of these methods to do workCmdlets override one or more of these methods to do work StartProcessing()StartProcessing()

Where one-time cmdlet startup operations are performedWhere one-time cmdlet startup operations are performed ProcessRecord()ProcessRecord()

Where cmdlets perform the bulk of their workWhere cmdlets perform the bulk of their work Processes a single object (e.g., record) at a timeProcesses a single object (e.g., record) at a time

EndProcessing()EndProcessing() Where one-time cmdlet close operations are performed Where one-time cmdlet close operations are performed

Page 11: Monad Shell – Task-Oriented Automation Framework

1111

Example: Get-Process cmdletExample: Get-Process cmdlet

……

using using System.Management.Automation;System.Management.Automation;

[CmdletDeclarationAttribute[CmdletDeclarationAttribute (“get”, “process”)] (“get”, “process”)]

public class public class GetProcess: CmdletGetProcess: Cmdlet

{{

public override void public override void StartProcessingStartProcessing()()

{{

WriteObjectsWriteObjects (Process.GetProcess()); (Process.GetProcess());

}}

}}

Page 12: Monad Shell – Task-Oriented Automation Framework

1212

PipelinesPipelines

Cmdlets execute in pipelines (Cmdlets execute in pipelines (A A B B C C)) Cmdlet attribution defines parameters for driving the parser Cmdlet attribution defines parameters for driving the parser Pipeline Processor manages cmdlet execution and Pipeline Processor manages cmdlet execution and

communicationcommunication Cmdlets communicate indirectly through objectsCmdlets communicate indirectly through objects

Each cmdlet execution has its own input/outputEach cmdlet execution has its own input/output Cmdlets execute in same thread as pipelineCmdlets execute in same thread as pipeline

Remoted cmdlet executes in a separate pipelineRemoted cmdlet executes in a separate pipeline Different computer, different processDifferent computer, different process Input/output for remoted cmdlet is serialized between pipelinesInput/output for remoted cmdlet is serialized between pipelines

Cmdlets use extended reflection to operate on objects Cmdlets use extended reflection to operate on objects independent of type independent of type MSHObject provides developers a common interface to access MSHObject provides developers a common interface to access

methods, properties, brokered methods, brokered properties, methods, properties, brokered methods, brokered properties, property sets, …property sets, …

Page 13: Monad Shell – Task-Oriented Automation Framework

1313

RequestRequest

Command ParserCommand Parser

ProcessProcess

ProcessProcess

RequestRequest

processprocesscmdletcmdlet

processprocessrequestrequestobjectobject

WhereWhere

WhereWhere

wherewherecmdletcmdlet

wherewhererequestrequestobjectobject

SortSort

SortSort

sortsortcmdletcmdlet

sortsortrequestrequestobjectobject

Out/TableOut/Table

TableTableout-chartout-chartrequestrequestobjectobject

Pipeline ProcessorPipeline Processor

out-chartout-chartcmdletcmdlet

get-process | where “handlecount –gt 400” | sort handlecountget-process | where “handlecount –gt 400” | sort handlecount | out-chart processname,handlecount| out-chart processname,handlecount

Pipeline ProcessingPipeline Processing

Page 14: Monad Shell – Task-Oriented Automation Framework

1414

ParametersParameters

Cmdlets request parameters from Cmdlets request parameters from Command lineCommand line Incoming pipeline objectsIncoming pipeline objects

Cmdlets define parameters as fields and mark them with Cmdlets define parameters as fields and mark them with metadata metadata [ParsingParameterDeclaration] [ParsingParameterDeclaration] [ParsingMandatoryParameter] [ParsingMandatoryParameter] [ParsingAllowPipelineInput][ParsingAllowPipelineInput] [ParsingParameterMapping(index)] [ParsingParameterMapping(index)] ……

MSH ensures parameters are filled in and validated MSH ensures parameters are filled in and validated before cmdlet ProcessRecord() method is calledbefore cmdlet ProcessRecord() method is called

Page 15: Monad Shell – Task-Oriented Automation Framework

Example: Stop-Process Example: Stop-Process cmdlet With Parametercmdlet With Parameterusing System.Management.Automationusing System.Management.Automation[CmdletDeclarationAttribute (“stop”, “process”)][CmdletDeclarationAttribute (“stop”, “process”)]public class StopProcess: Cmdletpublic class StopProcess: Cmdlet{{ [ParsingMandatoryParameter][ParsingMandatoryParameter]

[ParsingParameterMapping(0)][ParsingParameterMapping(0)][ParsingAllowPipelineInput][ParsingAllowPipelineInput][ParsingPromptString(“Name of the process: ")][ParsingPromptString(“Name of the process: ")]public string ProcessName;public string ProcessName;

public override void StartProcessing()public override void StartProcessing(){{ Process [ ]ps;Process [ ]ps;

ps = Process.GetProcessesByName(ProcessName);ps = Process.GetProcessesByName(ProcessName); foreach (Process p in ps)foreach (Process p in ps) {{ if (if (ShouldProcessShouldProcess(p.ProcessName))(p.ProcessName)) {{ p.Kill();p.Kill(); }} }}

}}}}

Page 16: Monad Shell – Task-Oriented Automation Framework

1616

get-process | where “handlecount –gt 400” | sort handlecountget-process | where “handlecount –gt 400” | sort handlecount | out-chart processname,handlecount| out-chart processname,handlecount

Error HandlingError Handling

Cmdlets communicate success and failure via Cmdlets communicate success and failure via queue objects queue objects 1 input queue, 2 output queues (success, error)1 input queue, 2 output queues (success, error) Additional streams for verbose, progress, and debugAdditional streams for verbose, progress, and debug

Errors are first class citizensErrors are first class citizens Errors can be reported immediatelyErrors can be reported immediately Cmdlets and pipelines can partially succeedCmdlets and pipelines can partially succeed

get-processget-process get-processget-processsuccess queuesuccess queue

get-processget-processerror queueerror queue

wherewhere

wherewhereerror queueerror queue

wherewheresuccess queuesuccess queue

……

Page 17: Monad Shell – Task-Oriented Automation Framework

1717

Cmdlet ProvidersCmdlet Providers

Cmdlet class provides common interfaces for writing cmdletsCmdlet class provides common interfaces for writing cmdlets CmdletProvider classes expose APIs for writing cmdlet providersCmdletProvider classes expose APIs for writing cmdlet providers Each cmdlet provider inherits a common set of core cmdletsEach cmdlet provider inherits a common set of core cmdlets Cmdlet providers should be written for Cmdlet providers should be written for

Configuration stores that can be navigatedConfiguration stores that can be navigated Containers where new, move, copy, rename, and remove operations can Containers where new, move, copy, rename, and remove operations can

be performedbe performed

Cmdlet ClassCmdlet Class

cmdletcmdlet cmdletcmdlet cmdletcmdlet Core cmdletsCore cmdlets(get, set, push, pop, …)(get, set, push, pop, …)

CmdletProvider ClassesCmdletProvider Classes

FileFileSystemSystem RegistryRegistry ActiveActive

DirectoryDirectory……

Page 18: Monad Shell – Task-Oriented Automation Framework

1818

Cmdlet/Provider Configuration Cmdlet/Provider Configuration And RegistrationAnd Registration

Cmdlet file naming is Cmdlet file naming is verb-noun.cmdletverb-noun.cmdlet and contains and contains Assembly binding informationAssembly binding information Help file binding informationHelp file binding information Syntax (metadata) informationSyntax (metadata) information

Cmdlet files can be generated using export-cmdlet utilityCmdlet files can be generated using export-cmdlet utility Reflects on .NET assemblies to produce .cmdlet filesReflects on .NET assemblies to produce .cmdlet files

Cmdlets are discovered by searching for .msh or .cmdlet Cmdlets are discovered by searching for .msh or .cmdlet files based on environment path variable settingsfiles based on environment path variable settings $MSHCOMMANDPATH, $PATH, $PATHEXT$MSHCOMMANDPATH, $PATH, $PATHEXT

At startup MSH reads profile.msh At startup MSH reads profile.msh profile.msh is used to create a set of valid functions and aliases profile.msh is used to create a set of valid functions and aliases

Page 19: Monad Shell – Task-Oriented Automation Framework

1919

Demo: Retrieving A List Of Demo: Retrieving A List Of Running ProcessesRunning Processes get-process | where “handlecount –gt 400” | sort handlecount get-process | where “handlecount –gt 400” | sort handlecount

ProcessName Id HandleCount WorkingSetProcessName Id HandleCount WorkingSet------------------- --- ----------------- ---------------------------------- --- ----------------- ---------------csrss 636 433 1191936csrss 636 433 1191936explorer 1600 447 9428992explorer 1600 447 9428992CcmExec 1880 523 16171008CcmExec 1880 523 16171008lsass 716 543 851968lsass 716 543 851968winlogon 660 644 5951488winlogon 660 644 5951488OUTLOOK 1320 1138 38465536OUTLOOK 1320 1138 38465536svchost 1020 1401 26091520svchost 1020 1401 26091520

Explanation of what the above script doesExplanation of what the above script does get-processget-process retrieves a list of running processes retrieves a list of running processes where where filters the filters the get-process get-process results to retain only processes with results to retain only processes with

more than 400 open handlesmore than 400 open handles sort handlecountsort handlecount orders the orders the sort sort results by # of open handles results by # of open handles

Page 20: Monad Shell – Task-Oriented Automation Framework

2020

Demo: Using MSH To Demo: Using MSH To Generate A ReportGenerate A Report get-process | where “handlecount –gt 400” get-process | where “handlecount –gt 400”

| sort handlecount | out-chart | sort handlecount | out-chart processname,handlecountprocessname,handlecount

Explanation of what the above script doesExplanation of what the above script does get-processget-process retrieves a list of running processes retrieves a list of running processes wherewhere filters the filters the get-processget-process results to retain only processes with results to retain only processes with

more than 400 open handlesmore than 400 open handles sort handlecountsort handlecount orders the orders the sort sort results by # of open handlesresults by # of open handles out-chartout-chart writes the writes the where where results to an Excel chart using results to an Excel chart using

processname and associated handlecount values processname and associated handlecount values

Page 21: Monad Shell – Task-Oriented Automation Framework

2121

Call To ActionCall To Action

Sign up for Command Shell Preview from Sign up for Command Shell Preview from betaplacebetaplace

Install itInstall it Use itUse it

Write SCRIPTSWrite SCRIPTS Write CmdletsWrite Cmdlets Write ProvidersWrite Providers

Give us feedback, early and oftenGive us feedback, early and often Help us ship the V1 that meets your Help us ship the V1 that meets your

needsneeds

Page 22: Monad Shell – Task-Oriented Automation Framework

2222

Additional ResourcesAdditional Resources

Web ResourcesWeb Resources Available on Available on http://http://betaplace.combetaplace.com

Use the guest account: Use the guest account: mshPDCmshPDC Logon and password e-mailed within Logon and password e-mailed within

24 hours24 hours Download bits, SDK, samples, private Download bits, SDK, samples, private

newsgroup, and a feedback/bug reporting newsgroup, and a feedback/bug reporting environmentenvironment

Page 23: Monad Shell – Task-Oriented Automation Framework
Page 24: Monad Shell – Task-Oriented Automation Framework

2424

MSH ArchitectureMSH Architecture

Monad Core Engine

Script & Parser Engine

MMC 2.1 MSH.exe

MetaData Processor

PipeLine Processor

CmdLet Setup

Config/Registration

Logging/Auditing

Intellisence/Metadata Access

Loader

Help Cmdlet

To System Auditing/Crimson

WebServicesOR

Any Agent

Error & Event

Handler

Session State & Jobs

Type Coercion & Extended Reflection

Internet/Intranet

MSH*.dll

Database Store

FileSystem

StdIn and StdOut

Out of ProcTo system services/

applications

ReqObj and CmdLet Obj

Management CmdLet

IIS or AD or Exch or SQL

ReqObj and CmdLet Obj

Non-Management

CmdLet

Legacy Utilities

Monad Remoting

WMX

Host-Speific Components

Host-Independent Components

Page 25: Monad Shell – Task-Oriented Automation Framework

2525

Scripting LanguageScripting Language Cmdlet syntax: <verb>-<noun> [-<qualifier> <value> [,<value>…] …] Cmdlet syntax: <verb>-<noun> [-<qualifier> <value> [,<value>…] …]

Verb refers to the action Verb refers to the action Noun refers to the system objectNoun refers to the system object Qualifier-value pair refers to the parameterQualifier-value pair refers to the parameter

Language constructsLanguage constructs arithmetic binary operators (+, -, * /, %)arithmetic binary operators (+, -, * /, %) assignment operators (=, +=, -=, *=, /=, %=)assignment operators (=, +=, -=, *=, /=, %=) comparison operators (-eq, ==, -ne, !=, -gt, -ge, -lt, -le)comparison operators (-eq, ==, -ne, !=, -gt, -ge, -lt, -le) logical operators (!, -and, -or)logical operators (!, -and, -or) unary operators (++, --, +, -)unary operators (++, --, +, -) redirection operators (>, >>)redirection operators (>, >>) arrays and associative arrays (hash tables)arrays and associative arrays (hash tables) boolean, stringboolean, string break, continue, returnbreak, continue, return comparisonscomparisons for, foreach, whilefor, foreach, while if, elseif, elseif, elseif, else functions, method calls, invoke (&)functions, method calls, invoke (&) propertiesproperties variablesvariables scopingscoping

Page 26: Monad Shell – Task-Oriented Automation Framework

2626

Base CmdletsBase Cmdlets ProvidersProviders

new-providernew-provider get-providerget-provider remove-providerremove-provider

DrivesDrives new-drivenew-drive get-driveget-drive remove-driveremove-drive

LocationLocation get-locationget-location set-locationset-location push-locationpush-location pop-locationpop-location

ChildrenChildren get-childrenget-children

ItemItem new-itemnew-item get-itemget-item set-itemset-item remove-itemremove-item rename-itemrename-item copy-itemcopy-item move-itemmove-item clear-itemclear-item invoke-iteminvoke-item

PropertyProperty new-propertynew-property get-propertyget-property set-propertyset-property remove-propertyremove-property rename-propertyrename-property copy-propertycopy-property move-propertymove-property clear-propertyclear-property

Property ValueProperty Value get-propertyvalueget-propertyvalue set-propertyvalueset-propertyvalue add-propertyvalueadd-propertyvalue remove-remove-

propertyvaluepropertyvalue clear-propertyvalueclear-propertyvalue

ContentContent add-contentadd-content get-contentget-content set-contentset-content clear-contentclear-content

PathPath test-pathtest-path convert-pathconvert-path parse-pathparse-path resolve-pathresolve-path combine-pathcombine-path

Page 27: Monad Shell – Task-Oriented Automation Framework

More CmdletsMore Cmdlets ProcessProcess

get-processget-process set-processset-process stop-processstop-process

ServiceService get-serviceget-service set-serviceset-service start-servicestart-service stop-servicestop-service

PipelinePipeline pick-objectpick-object sort-objectsort-object group-objectgroup-object measure-objectmeasure-object compare-objectcompare-object

EnvironmentEnvironment get-environmentget-environment set-environmentset-environment

HelpHelp get-helpget-help

AliasAlias new-aliasnew-alias get-aliasget-alias set-aliasset-alias remove-aliasremove-alias

HistoryHistory get-historyget-history eval-historyeval-history import-historyimport-history

VariableVariable new-variablenew-variable get-variableget-variable set-variableset-variable add-variableadd-variable remove-variableremove-variable

FileFile in-filein-file out-fileout-file

FormatFormat format-tableformat-table format-listformat-list format-wideformat-wide format-defaultformat-default format-objectformat-object

XMLXML convert-xmlconvert-xml test-xmltest-xml converto-mshxmlconverto-mshxml convertfro-mshxmlconvertfro-mshxml invoke-xsltinvoke-xslt

OutputOutput out-consoleout-console out-printerout-printer out-chartout-chart

ExpressionsExpressions reduce-expressionreduce-expression apply-expressionapply-expression

Page 28: Monad Shell – Task-Oriented Automation Framework

And Even More Cmdlets …And Even More Cmdlets … RunspaceRunspace

new-runspacenew-runspace wait-runspacewait-runspace remove-runspaceremove-runspace push-runspacepush-runspace pop-runspacepop-runspace test-runspacetest-runspace import-runspaceimport-runspace export-runspaceexport-runspace

SecuritySecurity get-securitydescriptorget-securitydescriptor set-securitydescriptorset-securitydescriptor get-securitycontextget-securitycontext get-credentialget-credential set-credentialset-credential get-signatureget-signature set-signatureset-signature test-signaturetest-signature

ConsoleConsole get-consoleget-console set-consoleset-console write-consolewrite-console read-consoleread-console

UtilityUtility get-dateget-date get-localizedstringget-localizedstring write-objectwrite-object write-errorobjectwrite-errorobject set-debugset-debug write-debugwrite-debug write-verbosewrite-verbose write-progresswrite-progress add-noteadd-note start-subshellstart-subshell get-cultureget-culture set-cultureset-culture

CommandCommand get-commandget-command eval-commandeval-command export-commandexport-command

ConfigurationConfiguration import-assemblyimport-assembly import-typexmlimport-typexml export-typexmlexport-typexml test-typexmltest-typexml update-typexmlupdate-typexml import-displayxmlimport-displayxml export-displayxmlexport-displayxml test-displayxmltest-displayxml update-displayxmlupdate-displayxml

Page 29: Monad Shell – Task-Oriented Automation Framework

2929

Interactive-ComposableInteractive-Composable

Command-line-orientedCommand-line-oriented Interactive experience (aliases, navigation, Interactive experience (aliases, navigation,

IntelliSense, command line editing)IntelliSense, command line editing) History (statement, status, and results)History (statement, status, and results) Help (rich schema and searching)Help (rich schema and searching) Pipelines (.NET and structures)Pipelines (.NET and structures) Utilities (reflection)Utilities (reflection)

Page 30: Monad Shell – Task-Oriented Automation Framework

3030

DemoDemoget-processget-process# Globbing applies to objects # Globbing applies to objects get-service A*get-service A*

# Descriptive names for cmds & params# Descriptive names for cmds & paramsstart-service -ServiceName Alerterstart-service -ServiceName Alerter

# only need to disambiguate# only need to disambiguatestop-service -S Alerterstop-service -S Alerter

# You can run any existing executable# You can run any existing executableipconfigipconfig

# You can invoke files# You can invoke filesdemo.txtdemo.txt

#Rich aliasing reduces typing#Rich aliasing reduces typingalias ps get-processalias ps get-processpsps

# Rich Navigation capabilities# Rich Navigation capabilitiescd c:\cd c:\pushd doc*\js*\msh*pushd doc*\js*\msh*popdpopd$CdPath$CdPathcd mshf*cd mshf*

get-historyget-history

# Object pipeline and utilities# Object pipeline and utilitiesgps |membergps |membergps |where "handlecount -ge 400" |sort handlecountgps |where "handlecount -ge 400" |sort handlecount

gps |sort MainModule.FileVersioninfo.companyName,handlecount |gps |sort MainModule.FileVersioninfo.companyName,handlecount |table -groupby MainModule.FileVersionInfo.CompanyName table -groupby MainModule.FileVersionInfo.CompanyName processname,handlecountprocessname,handlecount

gps msh |pick ProcessName -expand modules |table gps msh |pick ProcessName -expand modules |table processname,filenameprocessname,filename

gps |pick processname -expand modules |where "filename -like gps |pick processname -expand modules |where "filename -like *ntdll.dll" |table processname*ntdll.dll" |table processname

gps |pick processname -expand modules |group filename |sort gps |pick processname -expand modules |group filename |sort count -desc |head 15 |table count:6,name:70count -desc |head 15 |table count:6,name:70

# we don't limit ourselves to the console window# we don't limit ourselves to the console windowgps |out-grid processname,id,handlecountgps |out-grid processname,id,handlecountgps |sort handlecount |tail 10 |out-chart processname,handlecountgps |sort handlecount |tail 10 |out-chart processname,handlecountgps |out-excel processname,handlecount,id,workingsetgps |out-excel processname,handlecount,id,workingset

Page 31: Monad Shell – Task-Oriented Automation Framework

ProgrammableProgrammable

Rich, typed variables (read-only, constraints, Rich, typed variables (read-only, constraints, descriptions)descriptions)

Rich operators Rich operators Control structures (C# like with access to cmds Control structures (C# like with access to cmds

and utilities)and utilities) Functions (positional-named-typed-constrained Functions (positional-named-typed-constrained

params)params) Object property-method accessObject property-method access HostingHosting Glide path ( MMC => MSH => C# )Glide path ( MMC => MSH => C# ) Efficient cmdlet development modelEfficient cmdlet development model

Page 32: Monad Shell – Task-Oriented Automation Framework

3232

DemoDemo

# Typed variables# Typed variables$a = "string"$a = "string"$a = 1,2,3,4$a = 1,2,3,4$a = $(get-date)$a = $(get-date)$a = {get-date }$a = {get-date }$a.Invoke()$a.Invoke()

# Rich set of operators# Rich set of operators$i = 2$i = 2$s = "hello"$s = "hello"$i * 3$i * 3$s * 3$s * 3$i += 1$i += 1$s += "world"$s += "world"

$i = 10$i = 10$i % 3$i % 3$s = get-date$s = get-date"Today's data is {0:MM-YY-dd}" % s"Today's data is {0:MM-YY-dd}" % s

# C# like control structures # C# like control structures for ($i=0; $i -le 100 ; $i +=10 ) {$i }for ($i=0; $i -le 100 ; $i +=10 ) {$i }# But still have access to cmds# But still have access to cmdsforeach ($p in get-process |where "handlecount -ge 500" |sort foreach ($p in get-process |where "handlecount -ge 500" |sort handlecount ) { "{0,-15} has {1,6} Handles" % handlecount ) { "{0,-15} has {1,6} Handles" % $p.ProcessName,$p.Handlecount }$p.ProcessName,$p.Handlecount }

# We have scripts# We have scriptsedit test.mshedit test.mshget-console -prompt "Enter to get a list of processes"get-console -prompt "Enter to get a list of processes"get-processget-process

# We have functions# We have functionsedit test.mshedit test.mshfunction t1 {function t1 {get-console -prompt "Enter to get a list of processes"get-console -prompt "Enter to get a list of processes"get-processget-process}}

# Object property & method access# Object property & method access$s=$(new-stopwatch)$s=$(new-stopwatch)$s$s$s.Start()$s.Start()$s.Stop()$s.Stop()

Page 33: Monad Shell – Task-Oriented Automation Framework

3333

Easy To UseEasy To Use

File systems are easy to useFile systems are easy to use Navigation and manipulation are universalNavigation and manipulation are universal

Other stores are hard Other stores are hard Require domain-specific utilities Require domain-specific utilities

and conceptsand concepts

How do we make other stores easy?How do we make other stores easy? Interact with them as with file systemsInteract with them as with file systems

Page 34: Monad Shell – Task-Oriented Automation Framework

3434

DemoDemoget-drive -scope globalpushd hklm:\software\microsoftdircd wbemnew-item -path .\cimom -Name TEST1 -content "first TEST STRING" -type Stringnew-item -path .\xml\Decoders -Name TEST2 -content "Second TEST STRING" -type Stringnew-item -path .\wmic -Name TEST3 -content "Third TEST STRING" -type Stringnew-item -path . -Name TEST4 -content "Forth TEST STRING" -type String

get-children -recurse -include TEST*get-children -recurse -include TEST* |remove-item

dir c:\do*\*\*.mshdir c:\do*\*\*.msh -exclude *profile*

dir alias:c*dir env:dir variables:dir variables:*err*Dir AD:

Page 35: Monad Shell – Task-Oriented Automation Framework

3535

Production OrientedProduction Oriented

Uniform syntax, formatting, outputting, Uniform syntax, formatting, outputting, and processingand processing

Strong style guideStrong style guide NamingNaming ErrorsErrors TargetingTargeting

Admin friendly (Whatif, Confirm, Verbose)Admin friendly (Whatif, Confirm, Verbose) Rich error support ($error, -errvar, Rich error support ($error, -errvar,

-errorpolicy, error pipelines)-errorpolicy, error pipelines) Remote Management (Secure, 1:many)Remote Management (Secure, 1:many)

Page 36: Monad Shell – Task-Oriented Automation Framework

3636

DemoDemo

gps c*,s* -exc *t,*dgps c*,s* -exc *t,*dgps c*,s* -exc *t,*d |stop-process -whatifgps c*,s* -exc *t,*d |stop-process -whatifgps c*,s* -exc *t,*d |stop-process -confirmgps c*,s* -exc *t,*d |stop-process -confirm

stop-service a*stop-service a*$error$errorstop-service a* -errvar myvarstop-service a* -errvar myvar$myvar$myvarstop-service a* -errorpolicy notifycontinue stop-service a* -errorpolicy notifycontinue stop-service a* -errorpolicy silentcontinue stop-service a* -errorpolicy silentcontinue stop-service a* -errorpolicy notifystopstop-service a* -errorpolicy notifystopstop-service a* -errorpolicy inquirestop-service a* -errorpolicy inquire