68

Kirk Jackson Senior Developer, Xero Wellington.NET Users Group SVR308

Embed Size (px)

Citation preview

Page 1: Kirk Jackson Senior Developer, Xero Wellington.NET Users Group SVR308
Page 2: Kirk Jackson Senior Developer, Xero Wellington.NET Users Group SVR308

Windows PowerShell:The Future of Server Administration  Kirk JacksonSenior Developer, XeroWellington .NET Users Group

SVR308

Page 3: Kirk Jackson Senior Developer, Xero Wellington.NET Users Group SVR308

Session Level / Questions

Page 4: Kirk Jackson Senior Developer, Xero Wellington.NET Users Group SVR308

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]

Page 5: Kirk Jackson Senior Developer, Xero Wellington.NET Users Group SVR308

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

Page 6: Kirk Jackson Senior Developer, Xero Wellington.NET Users Group SVR308

Agenda

What is Windows PowerShell?Getting StartedUsing PowerShellScriptingAlternate Data Sources

Page 7: Kirk Jackson Senior Developer, Xero Wellington.NET Users Group SVR308

What is PowerShell?

Page 8: Kirk Jackson Senior Developer, Xero Wellington.NET Users Group SVR308

What is PowerShell?

The best shell scripting

environment for Windows

Page 9: Kirk Jackson Senior Developer, Xero Wellington.NET Users Group SVR308

What is PowerShell?

ObjectsConsistentDiscoverable

Page 10: Kirk Jackson Senior Developer, Xero Wellington.NET Users Group SVR308

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

Page 11: Kirk Jackson Senior Developer, Xero Wellington.NET Users Group SVR308

Admin: The Old Way

COM Componen

t

Command Line Tool

Admin ToolGraphical User

InterfaceWindows or Server Product Functionality

WMI Classes

Page 12: Kirk Jackson Senior Developer, Xero Wellington.NET Users Group SVR308

Admin: The New Way

Scripts

Windows PowerShell CmdLets

MMC Admin ToolGraphical User Interface

Windows or Server Product Functionality

Microsoft .NET Framework

Page 13: Kirk Jackson Senior Developer, Xero Wellington.NET Users Group SVR308

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

Page 14: Kirk Jackson Senior Developer, Xero Wellington.NET Users Group SVR308

Exchange 2007

Page 15: Kirk Jackson Senior Developer, Xero Wellington.NET Users Group SVR308

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

Page 16: Kirk Jackson Senior Developer, Xero Wellington.NET Users Group SVR308

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

Page 17: Kirk Jackson Senior Developer, Xero Wellington.NET Users Group SVR308

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

Page 18: Kirk Jackson Senior Developer, Xero Wellington.NET Users Group SVR308

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()

Page 19: Kirk Jackson Senior Developer, Xero Wellington.NET Users Group SVR308

Getting Started

Page 20: Kirk Jackson Senior Developer, Xero Wellington.NET Users Group SVR308

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

Page 21: Kirk Jackson Senior Developer, Xero Wellington.NET Users Group SVR308

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

Page 22: Kirk Jackson Senior Developer, Xero Wellington.NET Users Group SVR308

Set-ExecutionPolicy

RestrictedAll-SignedRemote-SignedUnrestricted

help set-executionpolicy –detailed

Page 23: Kirk Jackson Senior Developer, Xero Wellington.NET Users Group SVR308

Getting Started

demo

Page 24: Kirk Jackson Senior Developer, Xero Wellington.NET Users Group SVR308

Using PowerShell

Page 25: Kirk Jackson Senior Developer, Xero Wellington.NET Users Group SVR308

Top 4 Commands

1. Get-Command2. Get-Member3. Get-Help and -?4. Get-PSDrive

Page 26: Kirk Jackson Senior Developer, Xero Wellington.NET Users Group SVR308

Types of Commands

cmdletsShell function commandsScript commandsNative windows commands

command -parameter arg1 arg2write-output -inputobject “hello”

Page 27: Kirk Jackson Senior Developer, Xero Wellington.NET Users Group SVR308

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

Page 28: Kirk Jackson Senior Developer, Xero Wellington.NET Users Group SVR308

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

Page 29: Kirk Jackson Senior Developer, Xero Wellington.NET Users Group SVR308

Script command

PowerShell code written to a .ps1 fileLoaded from disk each time they are runOtherwise, the same as shell functions

Page 30: Kirk Jackson Senior Developer, Xero Wellington.NET Users Group SVR308

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

Page 31: Kirk Jackson Senior Developer, Xero Wellington.NET Users Group SVR308

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)

Page 32: Kirk Jackson Senior Developer, Xero Wellington.NET Users Group SVR308

Not your Fathers Pipeline

> first | second | third | fourth

PipelineCommand

… … …

> first | second | third | fourth | out-default

Page 33: Kirk Jackson Senior Developer, Xero Wellington.NET Users Group SVR308

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)

Page 34: Kirk Jackson Senior Developer, Xero Wellington.NET Users Group SVR308

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

Page 35: Kirk Jackson Senior Developer, Xero Wellington.NET Users Group SVR308

Using PowerShell

demo

Page 36: Kirk Jackson Senior Developer, Xero Wellington.NET Users Group SVR308

Top 4 Commands

1. Get-Command2. Get-Member3. Get-Help and -?4. Get-PSDrive

Page 37: Kirk Jackson Senior Developer, Xero Wellington.NET Users Group SVR308

Finding Commands

> Get-Command i*> Get-Command –Noun Process> Get-Command –Type {Alias | Function | Filter | Cmdlet | ExternalScript | Application | Script | All }

Page 38: Kirk Jackson Senior Developer, Xero Wellington.NET Users Group SVR308

Inspecting Objects

List all the properties and methods of an object> dir | get-member> dir | select Name | get-member

Page 39: Kirk Jackson Senior Developer, Xero Wellington.NET Users Group SVR308

Help

Man-page style help on language and commands

> Help> Help <command>

> <command> -?

> Help About_While> Get-Help * |Where {$_.Synopsis -match "process"}

Page 40: Kirk Jackson Senior Developer, Xero Wellington.NET Users Group SVR308

PowerShell Drive Providers

Expose alternate data sources as ‘drives’ for you to traverse> cd FUNCTION:> cd ENV:> ls

Page 41: Kirk Jackson Senior Developer, Xero Wellington.NET Users Group SVR308

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

Page 42: Kirk Jackson Senior Developer, Xero Wellington.NET Users Group SVR308

Common Parameters

WhatIf ConfirmVerboseDebugErrorAction ErrorVariable OutVariableOutBuffer

Page 43: Kirk Jackson Senior Developer, Xero Wellington.NET Users Group SVR308

Using PowerShell

demo

Page 44: Kirk Jackson Senior Developer, Xero Wellington.NET Users Group SVR308

Scripting

Page 45: Kirk Jackson Senior Developer, Xero Wellington.NET Users Group SVR308

Language Keywords

Only 13 keywords to learn:if (else, elseif)switch (default)forbreakdo, while, untilfunction, filterforeach

Page 46: Kirk Jackson Senior Developer, Xero Wellington.NET Users Group SVR308

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

Page 47: Kirk Jackson Senior Developer, Xero Wellington.NET Users Group SVR308

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.

Page 48: Kirk Jackson Senior Developer, Xero Wellington.NET Users Group SVR308

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

Page 49: Kirk Jackson Senior Developer, Xero Wellington.NET Users Group SVR308

Scripting

demo

Page 50: Kirk Jackson Senior Developer, Xero Wellington.NET Users Group SVR308

Creating a Function

$number = 7

$square = $number * $number

Page 51: Kirk Jackson Senior Developer, Xero Wellington.NET Users Group SVR308

Creating a Function

$number = 7

function square {$args[0] * $args[0]

}

square $number

Page 52: Kirk Jackson Senior Developer, Xero Wellington.NET Users Group SVR308

Creating a Function

$number = 7function square ( [int]$number = 1 ){

$number * $number}square $number

Page 53: Kirk Jackson Senior Developer, Xero Wellington.NET Users Group SVR308

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 }}

Page 54: Kirk Jackson Senior Developer, Xero Wellington.NET Users Group SVR308

Scripting

demo

Page 55: Kirk Jackson Senior Developer, Xero Wellington.NET Users Group SVR308

Alternate Data Sources

Page 56: Kirk Jackson Senior Developer, Xero Wellington.NET Users Group SVR308

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.

Page 57: Kirk Jackson Senior Developer, Xero Wellington.NET Users Group SVR308

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

Page 58: Kirk Jackson Senior Developer, Xero Wellington.NET Users Group SVR308

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

Page 59: Kirk Jackson Senior Developer, Xero Wellington.NET Users Group SVR308

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")

Page 60: Kirk Jackson Senior Developer, Xero Wellington.NET Users Group SVR308

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

Page 61: Kirk Jackson Senior Developer, Xero Wellington.NET Users Group SVR308

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/

Page 62: Kirk Jackson Senior Developer, Xero Wellington.NET Users Group SVR308

Resources

Page 63: Kirk Jackson Senior Developer, Xero Wellington.NET Users Group SVR308

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

Page 64: Kirk Jackson Senior Developer, Xero Wellington.NET Users Group SVR308

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

Page 65: Kirk Jackson Senior Developer, Xero Wellington.NET Users Group SVR308

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

Page 66: Kirk Jackson Senior Developer, Xero Wellington.NET Users Group SVR308

Evaluation Forms

Page 67: Kirk Jackson Senior Developer, Xero Wellington.NET Users Group SVR308

Questions?

Page 68: Kirk Jackson Senior Developer, Xero Wellington.NET Users Group SVR308

© 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.