View
214
Download
0
Category
Preview:
Citation preview
Around the data centre in 80 scripts
Richard Siddaway MVPMicrosoft Practice LeaderCentiq Ltd.Rsiddaway@centiq.co.uk
Introductions
I do not work for MicrosoftOpinions are MINEMicrosoft Practice Leader at CentiqInterests are optimisation, migration and managementAutomation = Script wherever possible
Worked with PowerShell since early betasStarted and lead UK PowerShell User GroupBlogging for 2 yearsPowerShell MVPDemos: Windows Server 2008 & PowerShell V2
Questions
WhoUses PowerShell ?Has seen PowerShell ?Uses another scripting language ?Automates administration ?
Attended February talk in Reading ?
Agenda
What is PowerShellPowerShell version 2BreakAdministering IIS 7Administering SQL Server
Remote Administration
Demo
WHAT IS POWERSHELL
Windows PowerShellWindows PowerShell
As interactive and composable as BASH/KSHAs programmatic as Perl/Python/RubyAs production oriented as AS400 CL/VMS DCLAllows access to data stores as easy as file system
SecurityInfrastructu
re
IT OperationsInfrastructu
re
Applications Infrastructu
re
Collaboration
Infrastructure
PowerShell
Automation engineCommand Shell and scripting language.NET based
DO NOT NEED TO LEARN .NET PROGRAMMING
RTW November 20062 million+ downloadsCTP 2 for Version 2 available since May
PowerShell – Key Features
Cmdlets
Providers
Extensible
Pipeline
The Difference is OBJECTS!
Get-Process | Where { $_.handles –gt 500 } | Sort handles | Format-Table
Get-P
rocess
Cm
dlet
Common Windows PowerShell Parser
Windows PowerShell Pipeline ProcessorW
here C
md
let
So
rt C
md
let
Fo
rmat
Cm
dlet
Script Types
Text.NET “interpretation” of the traditional Unix scripting model
COMWSH/VBScript style scripting
.NETManipulate any native .NET object
CommandsPowerShell cmdlets emitting objects
DataTypes
Flat File – CSV etc.NETXMLWMIADSIADO.NETSQL
PowerShell adoption
MicrosoftExchange 2007Windows Server 2008SC Data Protection ManagerSC Operations Manager 2007Compute ClusterSQL Server 2008OCS Resource Kit
Third partySpecial Operations SoftwareQuest AD cmdletsPowerGUIPowerGadgetsSdmsoftwareIBM Websphere MQPowerShell Community Extensions
Issues
Default install mode won’t run scriptsSet-ExecutionPolicy
No file associationCan’t automatically run scripts or double click
No remoting – coming in V2Can use .NET and WMI
Current working directory is NOT on PATH.\myscript.ps1
Does not load all .NET assembliesUse [Reflection.Assembly]::LoadWithPartialName(" Microsoft.SqlServer.Smo ")
Slow load?
Aliases
Please:
Do not use aliases in scripts or posts to forums, blogs or
articles etc
PowerShell Basics
Demo
Interactive
POWERSHELL VERSION 2
PowerShell V2
It is a CTP!! It will change!!!!!!! DO NOT USE IN PRODUCTION !!!!!!!RemotingBackground jobsScript CmdletsTransactions – depend on provider
Registry only
Debugging Graphical PowerShell
Win Remote Management
Jobs and RemotingWindows Remote Management Service
WinRM
WS-Management protocol
Local AND remote machinesRun as administrator
Configure AND use
PowerShell RunSpaces
RemotingLocal or remote machine
Creates PowerShell sessionPersistent connectionSpeeds response
PowerShell Jobs
Asynchronous PSJob – get, receive, remove, start, stop, wait
Start-Job or -AsJob
Local or remoteReceive-Job
View results (& delete job ?)
PowerShell Remoting
Need PowerShell local and remote
Invoke-Command or some cmdlets
Use a runspace
Can work with jobs
Script cmdlet
Script not compiledVariation on function
Works on pipeline
Cannot associate help fileSee get-help about_scriptcmdlet*
WMI
Instruments to access management information
Common Information Model V2
Windows 2000 onwards
Namespaces and classes
Local and remote machines
WMI in VBScript
strComputer = "." Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\CIMV2") Set colItems = objWMIService.ExecQuery( "SELECT * FROM Win32_Service",,48) For Each objItem in colItems Wscript.Echo "-----------------------------------" Wscript.Echo "Win32_Service instance" Wscript.Echo "-----------------------------------" Wscript.Echo "Name: " & objItem.Name Wscript.Echo "Status: " & objItem.StatusNext
WMI in PowerShell
Get-WMIObject Win32_Service | Select-Object Name, Status | Format-List
Or even:
gwmi win32_Service | select name, status | fl
WMI
WMI Type Accelerators[WMI][WMIClass][WMISearcher]
Improved support in V2Get-WMIObject improvedInvoke-WMIMethodSet-WMIInstanceRemove-WMIObject
PowerShell V2 issues
CTP = changingScripts may break
Check release notes
Cmdlet name clashesEspecially with PSCX
More complicatedNew keywords e.g. data
PowerShell V2
Demo
Break
ADMINISTERING IIS 7
IIS 7 and PowerShell
Microsoft.Web.AdministrationNew WMI provider
root\webadministrationNeed PowerShell V2 for remote accessCan use through .NET
PowerShell providerNot remotely
Remoting
IIS 7: .NET
Like any managed code assembly M.W.A requires explicit load into PowerShell before use
Do not forget to save your changes calling CommitChanges()
No access to remote machines Credentials issues
IIS 7: WMI
Needs packet privacy
MUST give credentials to access remotely
V1 Get-WMIObject cannot accessV2 can
Cannot create new objects remotelyAlternatives:
Access WMI via .NETUse remoting
IIS 7: WMI
IIS 7.0 introduced a new WMI namespace called “WebAdministration” in Vista, and it was enhanced in SP1 and Windows Server 2008WebAdministration is greatly simplified compared to IIS 6.0 WMI namespace (“MicrosoftIISv2”)WebAdministration is tightly integrated with IIS 7.0 configuration system, but provides more traditional set of objects: Site, Application, ApplicationPool, in addition to configuration sections
IIS 7: PowerShell provider
Download from www.iis.net
Provider and cmdlets
Currently CTP 2
IIS and Config file admin
IIS 7: Legacy support
The following options can be installed for IIS 7.0:
IIS 6 Scripting ToolsIIS 6 WMI CompatibilityIIS Metabase Compatibility
The goal behind these options is to allow existing ABO, ADSI, WMI code to continue to work on IIS 7.0Legacy scripts can only update legacy settings
Settings introduced for IIS 7.0 require the use of new APIs
Using IIS 7 through PowerShell
Demo
ADMINISTERING SQL SERVER
SMO
SQL Server Management Objects
Programmatic management of SQL Server
Extends and supersedes DMO
DOES NOT support compatibility level 60, 65 i.e. SQL 7 and above!
SMO Object Model
Server object is top level
Partial Object HierarchyDatabase
File groupStored ProcedureTable
LoginsLinked ServerSettings
SMO usage examples
Backup and RestoreDatabase Object searchIndex sizesDatabase, and log file sizesDatabase defragmentationManage
DatabaseTablesDatabase Users
SQL Server information
SMO and PowerShell
SMO part of SQL Server tool set
WILL work against remote machines
PowerShell does NOT load SMO assemblies
Create server object as start point
Using SMO in PowerShell
## This uses the SMO assemblies to retrieve SQL Server version information
##
## load SMO assemblies## use $null to prevent display of assembly
load information$null = [reflection.assembly]::LoadWithPartialName("Microsoft.SqlServer.ConnectionInfo")$null = [reflection.assembly]::LoadWithPartialName("Microsoft.SqlServer.SmoEnum")$null = [reflection.assembly]::LoadWithPartialName("Microsoft.SqlServer.Smo")
clear-host
Using SMO in PowerShell
## read input file and test for versionImport-Csv servers.csv | Foreach {
$svr = $_.Server
## set SMO variable $Server = New-Object
Microsoft.SqlServer.Management.Smo.Server($svr)
## get version information
$ver = $Server.Information.Properties | Where {$_.name -eq "VersionString"}
Using SMO in PowerShell
switch ($ver.Value.SubString(0,9)) {
"9.00.1399" {Write-Host $svr "SQL Server 2005 RTM"; break}
"9.00.2047" {Write-Host $svr "SQL Server 2005 SP1"; break}
"9.00.3042" {Write-Host $svr "SQL Server 2005 SP2"; break}
default {Write-Host $svr "version cannot be determined"; break}
}}
SQL Server 2008 Provider
Auto install of PowerShell v1 on Windows Server 2008PowerShell Provider
SQL Server as a file system!Object management NOT data access
Separate ShellSqlServerProviderSnapinSqlServerCmdletSnapin
Can invoke from Management Studio
SQL Server 2008 Provider
Based on SMOSQLServer
SQLSQLPolicy
Collection names are case sensitive!Databases
SQL Agent supports PowerShell job steps
SQL Server 2008 Provider
Specially compiled ShellCannot add other PowerShell functionality
Get\Remove\Add-PSSnapin not present
New-Item not supported – can’t create!Remove-Item is supportedCustom formattersUse Get-Item . to see system databases
SQL Server 2008 Provider
SqlServerCmdletSnapin cmdletsEvaluate-Policy
Invoke-Sqlcmd -Query "SELECT * FROM syslogins"
SQL Server 2008 Provider
SqlServerProviderSnapin cmdletsConvert-UrnToPath
Converts a SQL Server Management Object Uniform Resource Name (URN) to a SQL Server provider path.
Encode-SqlName "Table:Test" returns the string "Table%3ATest".Decode-SqlName "Table%3ATest" returns "Table:Test".
Using SQL Server through PowerShell
Demo
Summary/Call to Action
PowerShell can be used to administer large and growing parts of your environmentNow available at: www.microsoft.com/downloads
Search for PowerShell
Try it, Deploy it, Use it, Share
For More Information
User group:http://www.get-psuguk.org.uk
My Bloghttp://richardsiddaway.spaces.live.com
Get-PSUGUKUK PowerShellUser Group
Books
Books
Name: Richard SiddawayEmail: Rsiddaway@centiq.co.uk
Any Questions?
TechEd EMEA: Ask the Experts
Reference Slides
Scripting with COM
Access existing instrumentationBind to COM objects
$fso = New-Object -ComObject Scripting.FileSystemObject$m = [System.Runtime.InteropServices.Marshal]$word = $m::GetActiveObject("Word.Application")
Invoke methods/access properties$fso.GetDrive(“C:”)$fso.VolumeName = “System Drive”
Understand/extend instrumentationExtend and discover properties/methods
Update-TypeData Office.Word.Types.ps1xml$fso | Get-Member
Manipulate and format resultsDefine and import custom formating
Update-FormatData Office.Word.Format.ps1xml$word.RecentFiles | Sort name | Format-Table
Allows more simpler/more powerful COM scripts because of utilities and formatting
Scripting with WMI
PowerShell provides native WMI supportGet-WmiObject
Allows for inspection of WMI namespaceGet-WmiObject –list [-Namespace xx]Get-WmiObject –Class xx –Namespace xx –Property xxx – Filter xxx –ComputerName xxx –Credential xxx
Native language support[WMI] “\\JPSDESK10\root\cimv2:Win32_Process.Handle="0“[WMICLASS] "ROOT\cimv2:WIN32_PROCESS"[WMISEARCHER]"select * from Win32_process WHERE Name = 'calc.exe'"
Scripting with .NET
PowerShell provides native access to any .NET classCreate any object
[reflection.assembly]::LoadWithPartialName("System.Windows.Forms")$d = New-Object System.DateTime 2006,12,25
Access Properties/Invoke Methods$d.DayOfWeek$d.AddDays(-30)
Access Statics[DateTime]::Now[DateTime]::IsLeapYear(2006)
Allows admins to easily access and leverage a huge API set because of scriptability, utilities and formatting
Scripting with XML
PowerShell provides native XML supportNative datatype
$x=[xml]"<a><b><c>TEST</c></b></a>“$b =[xml](type c:\i386\mssecure.xml)
Native syntax to access “data” view of properties$b.BulletinDataStore.Bulletins.Bulletin[0]
Access to XML methods $b.BulletinDataStore.SelectNodes(“//Patch”)
XML properties available through PSBase property$b.BulletinDataStore.PSBase.innerXml
Scripting with Text
Invoke existing tools Existing command run directly after variables are expanded
Harvest data from existing toolsParse output into variables using text utilities.
Pipe data to SELECT and use –FIRST and –LAST Select-String <REGEX> <Path>Dir | Select-String <REGEX>[DateTime]”12/25/2006 7:00”([DateTime]”12/25/2006 7:00”).AddDays(-30)
Use functions/scripts to wrap the commands and convert output to objects or provide standard syntax
Safely process textUse CLR types via Windows PowerShell to safely parse text
[URI]” http://blogs.msdn.com/powershell/archive/2006/04/25/583234.aspx”
Allows admins to get 2-10x more power out of existing commands because of scriptability
Active Directory
AD cmdletshttp://www.quest.com/activeroles-server/arms.aspx
PowerGUIhttp://www.powergui.org
Special Operations Softwarehttp://www.specopssoft.com/
SDMSoftwarehttp://www.sdmsoftware.com/freeware.php
IIS 7
The following walkthroughs are available on the www.iis.net web site:
PowerShellAn Introduction to Windows PowerShell and IIS 7.0http://www.iis.net/go/1212Writing PowerShell Command-lets for IIS7http://www.iis.net/go/1211
AppCmdGetting Started with AppCmd in IIS 7.0http://www.iis.net/go/1222Command Line Administration with IIS7 – AppCmdhttp://www.iis.net/go/954
Recommended