kirk jackson senior developer, xero wellington.net users group svr308
TRANSCRIPT
Windows PowerShell:The Future of Server Administration Kirk JacksonSenior Developer, XeroWellington .NET Users Group
SVR308
Session Level / Questions
About the Speaker
Kirk JacksonSenior Developer, Xerohttp://www.xero.com Wellington .NET User Group organiserhttp://www.dot.net.nz/wellingtonMicrosoft MVP, ASP.NETBloghttp://[email protected]
Related Sessions
UNC308 - Microsoft Windows PowerShell Scripting for Microsoft Exchange Server 2007Johann KruseWed 15 Aug, 12:10-1:25pmSRV20 – Using PowerShell in Windows 2008Hands-on labAvailable throughout TechEdDEV311 - NET Framework 3.0 End-to-End: Putting the Pieces TogetherMatthew WinklerWed 15 Aug, 3:45-5:00pm
Agenda
What is Windows PowerShell?Getting StartedUsing PowerShellScriptingAlternate Data Sources
What is PowerShell?
What is PowerShell?
The best shell scripting
environment for Windows
What is PowerShell?
ObjectsConsistentDiscoverable
What is PowerShell?
New command line interface for WindowsScripting environment for WindowsNew programming language
Microsoft’s new platform for Server & Product administrationDesigned for the Windows environment
Admin: The Old Way
COM Componen
t
Command Line Tool
Admin ToolGraphical User
InterfaceWindows or Server Product Functionality
WMI Classes
Admin: The New Way
Scripts
Windows PowerShell CmdLets
MMC Admin ToolGraphical User Interface
Windows or Server Product Functionality
Microsoft .NET Framework
What uses PowerShell?
Exchange Server 2007Recipients, storage, transport, policy, serversUnderlies the GUI
System Center Operations ManagerSystem Center Data Protection Manager V2System Center Virtual Machine Manager
Install agents, explore objects, authoring, monitoring, alerts
Third parties: F5 Networks, Quest, ...Anything with WMI, COM, .NET interface
Exchange 2007
Exchange 2007Exchange Server 2003 (VBScript) E2K7 (PowerShell one-liner)
Mailbox Statistics
Set listExchange_Mailboxs = GetObject("winmgmts:{impersonationLevel=impersonate}!\\COMPUTERNAME\ROOT\MicrosoftExchangeV2").InstancesOf("Exchange_Mailbox")
For Each objExchange_Mailbox in listExchange_MailboxsWScript.echo "AssocContentCount =” + objExchange_Mailbox.AssocContentCountWScript.echo " DateDiscoveredAbsentInDS =” + objExchange_Mailbox.DateDiscoveredAbsentInDSWScript.echo " DeletedMessageSizeExtended =” + objExchange_Mailbox. DeletedMessageSizeExtendedWScript.echo " LastLoggedOnUserAccount =” + objExchange_Mailbox. LastLoggedOnUserAccountWScript.echo " LastLogoffTime =” + objExchange_Mailbox. LastLogoffTimeWScript.echo " LastLogonTime =” + objExchange_Mailbox. LastLogonTime WScript.echo " LegacyDN =” + objExchange_Mailbox. LegacyDNWScript.echo " MailboxDisplayName =” + objExchange_Mailbox. MailboxDisplayNameWScript.echo " MailboxGUID =” + objExchange_Mailbox. MailboxGUID WScript.echo " ServerName =” + objExchange_Mailbox. ServerName WScript.echo " Size =” + objExchange_Mailbox. SizeWScript.echo " StorageGroupName =” + objExchange_Mailbox. StorageGroupName WScript.echo " StorageLimitInfo =” + objExchange_Mailbox. StorageLimitInfo WScript.echo " StoreName =” + objExchange_Mailbox. StoreName WScript.echo " TotalItems =” + objExchange_Mailbox. TotalItems Next
get-mailboxstatistics –server $servername
Database Mgmt
Dim StorGroup as New CDOEXM.StorageGroup
StorGroup.DataSource.Open "LDAP://" + DCServer + "/ CN=First Storage Group,CN=InformationStore,CN=" + Server + ",CN=Servers,CN=First Administrative Group, CN=Administrative Groups,CN=First Organization, CN=Microsoft Exchange,CN=Services, CN=Configuration," + DomainName
StorGroup.MoveLogFiles("C:\newlogPath", 0)
move-storagegrouppath -identity “First Storage Group“ –log "C:\newlogPath”
Recipient Mgmt
Dim objMailbox As CDOEXM.IMailboxStore
Set objMailbox = GetObject("LDAP://" + DCServer + "CN=FOO,CN=users," + DomainName)
objMailbox.CreateMailbox "LDAP://" + DCServer + "/CN=Private MDB,CN=First Storage Group,CN=InformationStore,CN=" + Server + ",CN=Servers,CN=First Administrative Group, CN=Administrative Groups,CN=First Organization, CN=Microsoft Exchange,CN=Services, CN=Configuration," + DomainName
enable-mailbox -identity domain\FOO –database “First Storage Group\Private MDB”
>360 cmdlets are provided by the Exchange 2007 SnapIn http://technet.microsoft.com/en-us/library/bb124413.aspx
The Circle of AdminExplore at
the command line
Find the correct command
line(s) for the job
Parameterize in an
informal script
Formalize in a production
script
What’s wrong now?
What is wrong with cmd.exe?Weak languagePoor coverage / few utilitiesInsufficient / inflexible helpWindows is a GUI
What is wrong with bash / tcsh etc?Inconsistencies over the yearsText-orientedBasic scripting languages, poor library support
String versus Objects
$ ps -e | grep " p" | awk '{ print $1 }' | xargs kill
vsPS> get-process p* | stop-process
$ echo "this is a string" | tr '[a-z]' '[A-Z]' vsPS> "this is a string".ToUpper()
Getting Started
Getting Started
Pre-requisites:Windows Vista, Windows Server 2008,Windows XP SP2, Windows Server 2003.Net 2.0
Download from:http://www.microsoft.com/powershell
Join the communityNews GroupThe Blog http://blogs.msdn.com/powershell
Read the bundled documentation
Getting Started
No need to learn .NETExisting tools will all workNo need to learn the PowerShell languageLearn at your own paceTry using it instead of Command Prompt
Set-ExecutionPolicy
RestrictedAll-SignedRemote-SignedUnrestricted
help set-executionpolicy –detailed
Getting Started
demo
Using PowerShell
Top 4 Commands
1. Get-Command2. Get-Member3. Get-Help and -?4. Get-PSDrive
Types of Commands
cmdletsShell function commandsScript commandsNative windows commands
command -parameter arg1 arg2write-output -inputobject “hello”
cmdlets
129 provided cmdlets, you can add more> 360 cmdlets in Exchange 2007 SnapIncmdlets can be built using C#, VB.NETAlways named Verb-Noune.g. get-content, get-childitem,sort-object, select-object, where-objectcmdlets declare their parameters, the runtime parses them in a consistent waycmdlets can receive input from the pipeline
Shell functions
A piece of script code that has a nameLives in memory, temporarilyCan have parameters, or just work on all argumentsCan be entered interactively, or ‘dot-sourced’ ( . ./myfunc.ps1 )Can receive input from the pipeline
Script command
PowerShell code written to a .ps1 fileLoaded from disk each time they are runOtherwise, the same as shell functions
Native Windows Commands
Non-PowerShell / legacy commandsDon’t use PowerShell naming standards, parameter parsingOnly receive command line argumentsIf used in a pipeline, input is bundled up and sent as a string, output received as a stringRuns in a seperate process
Everything is an object
object = data + functionalityObjects have properties, which contain the data for that object (e.g. Name, Length)Objects have methods, which define the functionality of that object (e.g. Delete, MoveTo)Examples:
“a string” (String)42 (Integer)
Not your Fathers Pipeline
> first | second | third | fourth
PipelineCommand
… … …
> first | second | third | fourth | out-default
PowerShell Pipeline
No text, real objects are passed from one step to the nextFirst cmdlet generatesSubsequent cmdlets filter, sort, group, compare, ...Streaming means objects are passed along the pipeline when they are generatedAll commands run in-process (except native Windows commands)
Typing Tips
Aliases are defined for many cmdletscd instead of set-locationdir / ls instead of get-childitem
Parameters:Positional parameters don’t need their nameType as little of the parameter name as possible
When writing for other people, be sure to use expanded names
Using PowerShell
demo
Top 4 Commands
1. Get-Command2. Get-Member3. Get-Help and -?4. Get-PSDrive
Finding Commands
> Get-Command i*> Get-Command –Noun Process> Get-Command –Type {Alias | Function | Filter | Cmdlet | ExternalScript | Application | Script | All }
Inspecting Objects
List all the properties and methods of an object> dir | get-member> dir | select Name | get-member
Help
Man-page style help on language and commands
> Help> Help <command>
> <command> -?
> Help About_While> Get-Help * |Where {$_.Synopsis -match "process"}
PowerShell Drive Providers
Expose alternate data sources as ‘drives’ for you to traverse> cd FUNCTION:> cd ENV:> ls
Trusting Operations
Commands with side-effects support:Whatif
get-process | where {$_.handles –ge 500} | stop-process –WhatIf
Confirmstop-process S* -Confirm
Verbosestop-Process [a-x]*[q]*[r-t] -Verbose
Common Parameters
WhatIf ConfirmVerboseDebugErrorAction ErrorVariable OutVariableOutBuffer
Using PowerShell
demo
Scripting
Language Keywords
Only 13 keywords to learn:if (else, elseif)switch (default)forbreakdo, while, untilfunction, filterforeach
Language Constructs
Maths: + - * / % as normalAssignment: =, +=, -=, *=, /=, %=Boolean: -eq, -ne, -lt, -gt, -le, -ge, –and
–or, etc…Strings: -match, -notmatch, -like, -notlikeEscape: backticks `n, `t, `r etcLine continuation: backtick `Null value: $nullBoolean: $true / $false
Variables
Variables in PowerShell are created when they are first assignedUnassigned variables act as if they contain $null$_ contains ‘current object’ (match, pipeline value, loop value)$args contains unbound arguments to a functionThe type of the variable determines what happens when you add, mult, etc.
Language Constructs
$variable – a named variable$hash = @{ } – empty hash$hash[“key”] = $value$script = { … } – store a script&$script – run the script stored in $scriptArrays are wrapped and unwrapped transparently (usually a good thing)Convention: cmdlets are named verb-noun (e.g. get-content)Convention: singular, not plural
Scripting
demo
Creating a Function
$number = 7
$square = $number * $number
Creating a Function
$number = 7
function square {$args[0] * $args[0]
}
square $number
Creating a Function
$number = 7function square ( [int]$number = 1 ){
$number * $number}square $number
Creating a Function
function Get-Total ([String]$property = $(throw "Property Required"),[string]$formatString = "Total {1} = {0}") { Begin { $total = 0 } Process { $total += $_.$property } End { $formatString -f $total,$property }}
Scripting
demo
Alternate Data Sources
PSDrives
Data stores surfaced as “Drives”Filesystem, Registry, Alias, Certs, Env, Functions, Variables, etc.> Get-PSDrive> dir HKLM:\SOFTWARE\Microsoft
Each drive provider exposes PSDrivesItem, ChildItem, Content, ItemProperty, ACL, etc.
PSDrives
SharePoint drive provider:http://www.codeplex.com/PSSharePoint
Users, roles, websActive Directory Provider:http://www.codeplex.com/PowerShellCX/ SQL drive provider:http://tinyurl.com/2ycb66Zip drive provider:http://tinyurl.com/23j9cpNone of these are ready for primetime
WMI
Windows Management InstrumentationMonitor and control system components
Locally and remotelyPowerShell allows access to WMI classes and wraps in PowerShell objects
Get-WmiObject Win32_LogicalDiskGet-WmiObject Win32_ServiceGet-WmiObject win32_share
COM
Component Object ModelCOM and .NET talk nicely
PowerShell leverages this abilityUse new-object –comobject to createPowerShell wraps in an object
$ie = new-object -comobject InternetExplorer.Application
$ie.Navigate("www.google.com")
XML
XML can be loaded into PowerShell quite nicelyViewing the XML is as simple as traversing a tree of objectsModifying XML is not so pretty, and requires an understanding of .NET XML processing
Cool Tools
PowerShell gadgethttp://andrewpeters.net/powershell-gadget/Windows PowerShell graphical help filehttp://www.microsoft.com/downloads/details.aspx?familyid=3b3f7ce4-43ea-4a21-90cc-966a7fc6c6e8Codeplex - powershell community extensionshttp://www.codeplex.com/PowerShellCX/
Resources
Resources
Windows PowerShell Team blog: http://blogs.msdn.com/PowerShellWindows PowerShell ScriptCenter http://www.microsoft.com/technet/scriptcenter/hubs/msh.mspxhttp://www.codeplex.com/ShinyPower
What is PowerShell?
New command line interface for WindowsScripting environment for WindowsNew programming language
Microsoft’s new platform for Server & Product administrationDesigned for the Windows environment
Related Sessions
UNC308 - Microsoft Windows PowerShell Scripting for Microsoft Exchange Server 2007Johann KruseWed 15 Aug, 12:10-1:25pmSRV20 – Using PowerShell in Windows 2008Hands-on labAvailable throughout TechEdDEV311 - NET Framework 3.0 End-to-End: Putting the Pieces TogetherMatthew WinklerWed 15 Aug, 3:45-5:00pm
Evaluation Forms
Questions?
© 2007 Microsoft Corporation. All rights reserved. Microsoft, Windows, Windows Vista and other product names are or may be registered trademarks and/or trademarks in the U.S. and/or other countries.
The information herein is for informational purposes only and represents the current view of Microsoft Corporation as of the date of this presentation. Because Microsoft must respond to changing market conditions, it should not be interpreted to be a commitment on the part of Microsoft, and Microsoft cannot guarantee the accuracy of any information provided after
the date of this presentation. MICROSOFT MAKES NO WARRANTIES, EXPRESS, IMPLIED OR STATUTORY, AS TO THE INFORMATION IN THIS PRESENTATION.