comp075 os2
DESCRIPTION
Windows Power Shell. COMP075 OS2. What is it. A command line OS shell Replaces DOS CLI and .bat Also replaces Windows Script Host A bad idea from the start And netsh, and WMIC Built on .net Provides access to COM objects. .net?. - PowerPoint PPT PresentationTRANSCRIPT
What is it
• A command line OS shell
• Replaces DOS
– CLI and .bat
• Also replaces Windows Script Host
– A bad idea from the start
• And netsh, and WMIC
• Built on .net
– Provides access to COM objects
.net?
• A framework that, among other things provides access to COM objects
• It was intended to replace the COM interface by providing .net wrappers for the com objects
– Nevertheless, components like the office ribbon control are implemented using COM directly
• .net was intended to ease development by hiding implementation details
COM
• Component Object Model
• Introduced in 1993
• A language agnostic interface standard
– As opposed to, say, the C calling convention
• Basis for OLE, ActiveX, COM+ DCOM
• Used for IPC
• Supplanted DDE
DDE• Dynamic Data Exchange
• An IPC protocol that allowed text based “conversations” between processes
• The original basis for OLE
– Object Linking and Embedding
– Let you put spreadsheets in a word document
• Text conversations considered not flexible enough, so COM was introduced as the basis for OLE2 (later renamed OLE)
• COM designed for any software components
– Not just OLE
What was wrong with text, or simple binary interface?
• Too inflexible
• Format had to remain the same to be understood by the reading process
• Microsoft is really bad at leaving things alone
• Object interfaces avoid this problem
• Data extracted from interface by name
– So only the name has to be stable
• Objects know the format of the data and can inform the recipient
• Perfect for heterogeneous development environment where no one talks to each other
ActiveX
• Just before COM, MS introduced VBX
– Visual Basic Extensions
– C or C++ user interface subroutines meant to be called from Visual Basic main program
• These became OLE controls (OCXs) based on COM
• Later renamed ActiveX Controls for use in browsers
– Called controls since originally meant for user interface
– Actually general purpose programs
• Now all OLE is known as ActiveX except in MS Office
COM and the registry
• COM objects belong to classes
• They have interfaces and type definitions
• Stored in the registry
– HKEY_CLASSES_ROOT\CLSID for classes and HKEY_CLASSES_ROOT\Interface
• Registration-free COM stores these data in an XML manifest
• Registry use can introduce DLL hell since only one version can be registered
More .net
• Consists of FCL (Framework Class Library)
– User interface, data access, db connectivity, crypto, development, networking, graphic rendering XML manipulation
• And CLR (Common Language Runtime)
– An application VM providing security, memory management, exception handling etc
• Visual Studio is an IDE for .net programs
Some .net features
• Wrappers to provide access to COM objects
• Common Type System and Common Language Infrastructure specifications provide for language independence
• CLI implemented through CLR
• CLI program compiled to CIL (Common Intermediate Language) and stored in assemblies
Assemblies
• Code is in PE format
• Assemblies can comprise many files
• One is a manifest containing metadata
• Name is simple name + version + culture + public key token
• Considered the same if equal in all but revision
– Version = major + minor + build + revision
– This is meant to avoid DLL hell
• Can be process (exe) or library (dll) assembly
Public Key
• A Strongly Named assembly can be stored in the Global Assembly Cache
• Must have some components signed with private key corresponding to public key in the assembly name
• All versions of assembly must be signed by same key
• All assemblies depended on must be strongly named
• Global Assembly Cache can contain two versions of the same assembly, but file system can't
Power Shell and .net
• Most PS functions provided through commands
– But in PS are called cmdlets
• cmdlets are .net classes (programs)
• Can be combined into scripts or run in Win32 console
• Runtime can be embedded in other applications so that a cmdlet can access interfaces usually only available through a gui
• cmdlets can access COM objects and WMI through .net and file systems and registry through PS providers
Types of commands
• cmdlets
– Specially designed .net classes
– Run as part of the PS process
• PS scripts (.ps1)
• PS functions
– Subroutines, like in bash
• Standalone programs
– Run as separate process
cmdlets
• Names follow verb-noun pattern which makes them annoyingly large
– Get-Help
– But abbreviations are provided as aliases
• Input and output are .net objects, or collections of objects
– Not text
– Except command line parameter input
• Last stage in pipeline automatically sent to Out-Default cmdlet to convert object to text
cmdlet structure
• Class def may implement BeginProcessing, ProcessRecord and EndProcessing methods
• ProcessRecord required to process pipeline input
– Invoked once for each object in a collection
• Must have .net attribute “CmdletAttribute” containing cmdlet name
• ValueFromPipeline attribute distinguishes ParameterAttribute properties that originate in pipeline
pipelines
• | operator joins one cmdlet to another in a pipeline
• Like DOS or bash pipelines but .net objects rather than text
– Parsing or serializing not required
– Format doesn't matter, needn't remain stable
• Objects can use standard ToString() method to format attributes as text, or include custom formatters
Providers• Cmdlet can reference any .net API including
data access APIs
• Or use included PS providers
• Providers available for
– File system
– Registry
– Certificate store
– Namespace for aliases, variables and functions
– All looks like a file system (like linux but with drive letters)
• Some cmdlets access WMI
Command Names
• Verb-Noun format
• Restricted set of verbs
– Get New Restart Resume Set Start Stop Suspend
• Nouns used consistently across commands
• Two letter abbreviation aliases
– Remove-Item ri
– Copy-Item ci
– Move-Item mi
– Rename-Item rni
– Get-Content gc
Object Pipelines
• Like pipelines in DOS and bash, but data passed to next command in the form of an object
• Unlike text, data in an object have names and other attributes so next stage in pipeline can be aware of these metadata for formatting and other purposes
• To display in text form, last stage of pipeline is automatically Out-Host (oh)
• Get-member shows you the components of an input object
Out commands
• Out-Host (oh) converts to text
-paging outputs through pager
“more” is a function that acts as a synonym
• Out-Null Discards the output
• Out-Printer prints
• Out-File -FilePath … sends to a file
• Out- command has to be last in the pipeline
Format Commands
• format-wide
– Like dir /w
– Extracts one property (usually name), displays in two columns
• Format-table
– Table with property name headings
– The default
• Format-List
– Lines with property name, value
– Repeats for each object
Directories
• Get-Location (pwd) shows current directory
– Note: In PS this could be a network or other path including a registry path or the process environment
• Set-location (cd) changes directory
• cd ..
• “Push-location path” cd's and pushes to stack
• Pop-location pops from stack and cds
-passthru option also sends location to output
Drive Letters
• A more generalized concept
• a: c: etc as usual
• HKCU: HKLM: etc for root of registry trees
• Cert: for certificate store
• Env: for the process environment
• Get-psdrive lists available drives
Help!
• Get-command lists available commands
• Get-command get.* lists get commands
• gcm command1 -syntax gets syntax for command1
• Get-help command-name gets basic help
• Or command-name -?
• help command-name -examples
• man command-name -detailed
• help command-name -full
Scripts
• More like a real programming language
• Variables, literals, functions, control structures
• Variable names start with $
– Can be assigned output of a cmdlet
– Or any other value
• Literals can be single or double quoted like in bash or perl
• $args is the array of parameters
• Can use associative arrays (like perl hash)
Permission to Run Scripts
• ExecutionPolicy by default may forbid execution of scripts, or require that they be signed
• Set-executionpolicy bypass localmachine allows any script to run for anyone
• Like bash, PS doesn't search current directory for scripts
• To run script other than from path specify complete path
• .\menu.ps1 for script in current directory
– Note .ps1 for PS scripts
Conditions
man about_Comparison_operators
• -eq -ne -lt -gt -le -ge
– If left side is a list, returns nothing, or the values for which the comparison is true
– If left is a scalar returns true or false
• string -match/-notmatch regex
• Can test on the command line
2 -eq 2
true
switch Options
switch -regex (value)
{
regex {statement list}
…
• Break
– Switch statement will match multiple possibilities
– To prevent this put break statement at end of each statement list
• Arrays: If value is an array, each element is compared
while
while (condition) {
statement list
}
• break can be used to exit from the entire statement
mylabel: while …
break mylabel
• Label used to specify which loop to break from in case they were nested
Writing to the Screen
clear -- will clear the screen
• As will clear-host
echo $1 –Writes $1 to the screen
• As will
Output-Host -InputObject $1 (oh)
• Or
Write-Host $1
• Or just
$1
Asking the User for a Choice
• Three part process
• First: Create objects that define the choices
• Second: Create a menu object that offers these choices
• Third: Activate a menu with a Title, a message to the user, and the menu object
Define the Choices
• $First = New-Object System.Management.Automation.Host.ChoiceDescription "&First", "First Choice"
• $First contains the object
• First is the short description of the Choice
• &F makes “F” a hotkey for this choice
• "First Choice" appears if help is requested
Create Menu ObjectAsk for Choice
• $options = [System.Management.Automation.Host.ChoiceDescription[]] ($First, $second)
• $title = 'two choice menu'
• $message= “enter a choice”
• $result = $host.ui.PromptForChoice($title, $message, $options, 0)
A Possibly Easier Way
• read-host gets a value from the user and returns the value entered
$choice = read-host– Stores the value in $choice
• If you want, you can craft a menu and get a response this way, but you won't get the built in supports (like help text for the user, error handling) that the previous method provides
References
• Users Guide
– http://technet.microsoft.com/en-us/library/cc196356.aspx
• Tips
– http://technet.microsoft.com/en-us/library/ff730939.aspx