managing web infrastructure systems with windows powershell 2.0 demo script

30
SRV-300 Managing Web Infrastructure Systems with Windows PowerShell™ 2.0 Level 300 Demo Script Published: 12 th May 2009

Upload: microsoft-technet

Post on 07-Nov-2014

2.262 views

Category:

Technology


2 download

DESCRIPTION

This session will explore how Windows Powershell v2.0 can automate administrative tasks to manage critical web infrastructure systems in the data center. The session will include topics on how to monitor and manage Windows Server 2008 systems. We will discuss how to use Windows Powershell cmdlets and WMI to retrieve local and remote information and execute tasks that can be performed on a daily basis. Then we will focus on how Windows Powershell can make it easier for IT Professionals to manage Active Directory to administer network accounts and publish shared folders. Next, we will explore how Windows Powershell Snap-in for IIS can be used to efficiently manage web servers in a web farm to decrease administrative overhead. Then we will show you how Windows Powershell snap-in included in SQL Server 2008 can make it easier for IT Professionals to administer backend databases.

TRANSCRIPT

Page 1: Managing Web Infrastructure Systems with Windows PowerShell 2.0 Demo Script

SRV-300 Managing Web Infrastructure Systems with Windows PowerShell™ 2.0

Level 300

Demo Script

Published: 12th May 2009

Page 2: Managing Web Infrastructure Systems with Windows PowerShell 2.0 Demo Script

CONTENTS

BEFORE YOU BEGIN........................................................................................................................................................................................... 3

SEND US YOUR FEEDBACK ABOUT THIS SECTION...................................................................................................................................................... 3

DEMO 1: MANAGING WINDOWS SERVER®....................................................................................................................................................... 4

CHECK FOR HOTFIXES ON WINDOWS SERVER........................................................................................................................................................... 4USE WMI TO MANAGE SERVERS REMOTELY............................................................................................................................................................ 5MONITOR SERVER PERFORMANCE.......................................................................................................................................................................... 6SEARCH ACTIVE DIRECTORY FOR ACCOUNTS............................................................................................................................................................ 7SEARCH ACTIVE DIRECTORY FOR PUBLISHED FOLDERS............................................................................................................................................. 10SEND US YOUR FEEDBACK ABOUT THIS DEMONSTRATION......................................................................................................................................... 11

DEMO 2: MANAGING INTERNET INFORMATION SERVICES...............................................................................................................................12

MANAGE WEB SITES......................................................................................................................................................................................... 12ADD VIRTUAL DIRECTORIES AND APPLICATION POOLS.............................................................................................................................................. 13AUTOMATE WEB SITE CREATION.......................................................................................................................................................................... 14ADD FTP SITE................................................................................................................................................................................................. 16CONFIGURE IIS PROPERTIES................................................................................................................................................................................ 17USE WMI TO MANAGE WEB SITES....................................................................................................................................................................... 19SEND US YOUR FEEDBACK ABOUT THIS DEMONSTRATION......................................................................................................................................... 19

DEMO 3: MANAGING SQL SERVER.................................................................................................................................................................. 21

INITIALIZE SQL SERVER POWERSHELL ENVIRONMENT.............................................................................................................................................. 21WORK WITH SQL SERVER MANAGEMENT OBJECTS.................................................................................................................................................. 21STOP AND START SERVICES BY USING WMI.......................................................................................................................................................... 23USE INVOKE-SQLCMD CMDLET TO UPDATE A TABLE................................................................................................................................................ 24SEND US YOUR FEEDBACK ABOUT THIS DEMONSTRATION......................................................................................................................................... 25

©2009 Microsoft Corporation.  All Rights Reserved 2

Page 3: Managing Web Infrastructure Systems with Windows PowerShell 2.0 Demo Script

Chapter 1 Before you begin1. The Password for the images is Password1.2. Turn on SEA-DC-01 and logon as Contoso\Administrator.3. Turn on SEA-WEB-01 and logon as Contoso\Administrator.4. When pasting code into Windows PowerShell the steps indicate that you should right-click the Window PowerShell window and the

click Paste. Right-clicking the window may be all that is required in order to paste the code.

Chapter 2 Send Us Your Feedback about This Section

We appreciate hearing from you. To send your feedback, click the following link and type your comments in the message body.

Note The subject-line information is used to route your feedback. If you remove or modify the subject line we may be unable to process your feedback.

Send Feedback

©2009 Microsoft Corporation.  All Rights Reserved 3

Page 4: Managing Web Infrastructure Systems with Windows PowerShell 2.0 Demo Script

Chapter 3 Demo 1: Managing Windows Server®In the demonstration, we will explore several ways to manage Windows Server by using Windows PowerShell. We will check for hotfixes, use Windows Management Instrumentation (WMI) to remotely manage servers, and monitor performance. We will also use Windows PowerShell to search Active Directory and add Users and Shared Folders.

Chapter 4 Check for Hotfixes on Windows Server

Speaker Script StepsBefore we begin working with Windows PowerShell we will open our Windows PowerShell Scripts text file that contains code examples for some of the longer scripts that are used during this session.

Perform these steps on SEA-DC-01.1. On the desktop, double-click PowerShellScripts.

2. The PowerShellScripts notepad window opens. Maximize the window.

3. Minimize PowerShellScripts.

Now we will open Windows PowerShell version 2 and then look at working with hotfixes.

4. On the desktop, double-click Windows PowerShell V2.

5. The Windows PowerShell V2 window opens. Maximize the window.

The Get-Hotfix cmdlet gets the quick-fix engineering (QFE) updates that were applied to the local computer or to remote computers by Component-Based Servicing.

6. Type help get-hotfix and then press ENTER.

To get a list of all hotfixes installed on the local computer we just have to type the name of the cmdlet.

7. Type get-hotfix and then press ENTER.

This command gets the most recent hotfix on the computer. It gets the hotfixes, sorts them by the value of the InstalledOn property and then uses array notation to select the last item in the array.

8. Type (get-hotfix | sort installedon)[-1] and then press ENTER.

This command gets all hotfixes on the local computer that have a description that begins with "Security."

9. Type get-hotfix -description Security*, and then press ENTER.

This command creates a text file listing the names of computers that are missing a security update. The command uses the Get-Hotfix cmdlet to get the KB940518 update on all the computers whose names are listed in the Servers.txt file.

If a computer does not have the update, the Add-Content cmdlet writes the computer name in the Missing-KB940518 text file.

10. Restore PowerShellScripts.

11. Under the --- Check for missing Hotfox --- comment, select the text.

12. Right-click the selected text, and then click Copy.

13. Minimize PowerShellScripts.

Now we will run this script. 14. Right-click the PowerShell window, and then click Paste.

15. Press ENTER.

We can open the text file by calling Notepad from Windows PowerShell. In the text file we see both servers are listed which means that neither have update KB940518 installed.

16. Type notepad Missing-kb940518.txt, and then press ENTER.

17. The Notepad window opens. Maximize the window.

18. Point to the server names.

19. Close Notepad.

©2009 Microsoft Corporation.  All Rights Reserved 4

Page 5: Managing Web Infrastructure Systems with Windows PowerShell 2.0 Demo Script

Chapter 7 Microsoft ConfidentialChapter 8 – Microsoft Internal Use Only

Chapter 5 Use WMI to Manage Servers Remotely

Speaker Script StepsWe’re going to look at a script that gets WMI information from a remote computer and uses it to create a list of all running processes on the system, along with their working set sizes.

First, we’ll define a variable called processlist. We’ll use the get-wmiobject command to query the remote computer’s WMI namespace to retrieve process information. The get-wmiobject command will automatically connect to the local computer’s default namespace, root\CIMv2.

1. Type cls, and then press ENTER.

2. Type $processlist = get-wmiobject –query “select * from win32_process” -computername SEA-WEB-01, and then press ENTER.

After this, we’re ready to start the For Each loop. The first line here indicates that for every process returned by the query, we’re going to perform a set of operations.

3. Type foreach ($process in $processlist), and then press ENTER.

4. Type {, and then press ENTER.

We’ll create a variable that contains a single line of text that we want to write to the file. This includes the process name and working set size and text to make the output easier to read.

5. Type $listitem = “Process “+$process.name+” has a working set size of “+$process.workingsetsize, and then press ENTER.

When we're done with the line of text we want to write, we’ll use the out-file command to actually write the line to the file.

6. Type out-file –filepath “C:\processworkingset-ps.txt” –inputobject $listitem –append, and then press ENTER.

7. Type }, and then press ENTER.

We’ll use the write-host command to write a line of text to the screen to let us know when the script is finished.

8. Type write-host “Process Listing Complete”, and then press ENTER.

9. Press ENTER.

The text file that was created by the script has a nicely formatted list of process names and their working set sizes, with one line for each process.

10. Type notepad c:\processworkingset-ps.txt, and then press ENTER.

11. The Notepad window opens. Maximize the window.

12. Point to the first line of text.

13. Close Notepad.

Now we will see a simple example of remote management using WMI. On our Web server we will stop the Netlogon service. This will simulate a connection or authentication problem on the server.

Perform these steps on SEA-WEB-01.14. On the desktop, double-click Services.

15. The Services window opens. Maximize the window.

16. Right-click Netlogon, and then click Stop.

We can then check the state of the Netlogon service by using WMI from our domain controller. We will connect to the WMI service on the SEA-WEB-01

Perform these steps on SEA-DC-01.17. Type Get-WmiObject -computer SEA-WEB-01

©2009 Microsoft Corporation.  All Rights Reserved 5

Page 6: Managing Web Infrastructure Systems with Windows PowerShell 2.0 Demo Script

Chapter 7 Microsoft ConfidentialChapter 8 – Microsoft Internal Use Only

computer and retrieve all instances of the Win32_Service class where the Name property is equal to Netlogon.

We can see that the current state is Stopped.

Win32_Service -Filter "Name='Netlogon'", and then press ENTER.

We can use the same statement to connect to the WMI service but we add two things. First we add parentheses around the Get-WMIObject statement. This ensures that Windows PowerShell treats the returned object as an object so that we have something we can call a method on.

The second addition is where we call InvokeMethod and pass it two parameters; StartService, the name of the WMI method we want to invoke, and $Null, which indicates a Null value. InvokeMethod expects two parameters: the method to be called, followed by any additional arguments needed by the method. In this case there are no method arguments. But InvokeMethod expects two parameters whether those parameters exist or not. So we passed a null value as the second parameter.

18. Type (Get-WmiObject -computer SEA-WEB-01 Win32_Service -Filter "Name='Netlogon'").InvokeMethod("StartService",$null), and then press ENTER.

We can then run our original Get-WMIObject statement to verify that the service in now in a running state, which it is.

19. Press the UP ARROW twice.

20. Press ENTER.

We can also go to the Web Server and verify that the service is running in the Services window.

Perform these steps on SEA-WEB-01.21. In the Services window, click the Refresh toolbar button.

22. Point to Netlogon.

23. Close Services.

Chapter 6 Monitor Server Performance

Speaker Script StepsThe Get-Counter cmdlet gets live, real-time performance counter data directly from the performance monitoring instrumentation in Windows. You can use it to get performance data from the local or remote computers at the sample interval that you specify.

You can use the parameters of Get-Counter to specify one or more computers, to list the performance counter sets and the counters that they contain, and to set the sample size and interval, and to specify the credentials of users who have permission to collect performance data.

Perform these steps on SEA-DC-01.1. Type cls, and then press ENTER.

2. Type get-help get-counter, and then press ENTER.

This command gets the current percentage of free space and total free space on the SEA-WEB-01 server. We specify the performance counters by using the Counter parameter. We also specify the computer by using the ComputerName parameter.

3. Type Get-Counter -Counter "\logicaldisk(c:)\% Free Space","\logicaldisk(c:)\Free Megabytes" -MaxSamples 1 -ComputerName SEA-WEB-01, and then press ENTER.

©2009 Microsoft Corporation.  All Rights Reserved 6

Page 7: Managing Web Infrastructure Systems with Windows PowerShell 2.0 Demo Script

Chapter 7 Microsoft ConfidentialChapter 8 – Microsoft Internal Use Only

If you are not sure which counter sets are available then you can use the ListSet parameter. If you type an asterisk, or wildcard, for the ListSet value then it will return all counters sets on the computer. In this case we will use HTTP with a wildcard which returns three counter sets related to HTTP.

4. Type Get-Counter -ListSet HTTP*, and then press ENTER.

You can use the Path property of a counter set to find the correctly formatted path names for the performance counters. This command gets the path names of the performance counters in the Memory counter set on the local computer.

5. Type (Get-Counter -Listset memory).paths, and then press ENTER.

This command gets the current available memory and pages per second on the SEA-WEB-01 server.

Performance counters are often protected by ACLs. To get all available performance counters, open Windows Power Shell with the "Run as administrator" option when you use Get-Counter.

6. Type Get-Counter -Counter "Memory\Available Bytes","\Memory\Pages/sec" -MaxSamples 1 -ComputerName SEA-WEB-01, and then press ENTER.

This command gets the current percentage of processor time combined values for all processors on the local computer. It collects data every two seconds until it has three values.

We specify the maximum number of samples to get from each counter by using the MaxSamples parameter. The default is no maximum, that is, Get-Counter collects and returns data until you interrupt it by pressing CTRL + C.

The SampleInterval parameter specifies the time between samples in seconds. The minimum value and the default value are one second.

7. Type Get-Counter -Counter "\Processor(_Total)\% Processor Time" -SampleInterval 2 -MaxSamples 3 -ComputerName SEA-WEB-01, and then press ENTER.

This last command gets the current connections to the Web Service and the connection attempts per second on the SEA-WEB-01 server. It collects data until it has two values.

8. Type Get-Counter -Counter "Web Service(*)\Current Connections","Web Service(*)\Connection Attempts/sec" -MaxSamples 2 -ComputerName SEA-WEB-01, and then press ENTER.

Chapter 7 Search Active Directory for Accounts

Speaker Script StepsThis first sample code works equally well on both versions of Windows PowerShell. There are different ways that you could perform this task but here is one example.

First we will specify an LDAP search filter. This particular search filter combines two criteria: it searches for everything that has an objectCategory equal to User and a Department equal to Finance.

1. Type cls, and then press ENTER.

2. Type $strFilter = "(&(objectCategory=User)(Department=Finance))", and then press ENTER.

©2009 Microsoft Corporation.  All Rights Reserved 7

Page 8: Managing Web Infrastructure Systems with Windows PowerShell 2.0 Demo Script

Chapter 7 Microsoft ConfidentialChapter 8 – Microsoft Internal Use Only

Now we have to identify the Active Directory location where we want the search to begin. We won't specify an Active Directory location but if we create a DirectoryEntry object without any additional parameters we’ll automatically be bound to the root of the current domain.

If you want to start in a different location then include the ADsPath of the desired start location when you create the object.

3. Type $objDomain = New-Object System.DirectoryServices.DirectoryEntry, and then press ENTER.

After we have a DirectoryEntry object, and a starting location for our search, we will create an instance of the System.DirectoryServices.DirectorySearcher class. This is the object that actually performs an Active Directory search.

4. Type $objSearcher = New-Object System.DirectoryServices.DirectorySearcher, and then press ENTER.

Before we can begin using our DirectorySearcher object we have to assign values to several different properties of this object. The SearchRoot tells the DirectorySearcher where to begin its search.

5. Type $objSearcher.SearchRoot = $objDomain, and then press ENTER.

Next we assign the value 1000 to the PageSize property. By default, an Active Directory search returns only 1000 items. To have it return more items you need to assign a value to the PageSize property. When you do that, your search script will return that number of items, pause briefly, and then return the next group of items. This process will continue until all the items meeting the search criteria have been returned.

6. Type $objSearcher.PageSize = 1000, and then press ENTER.

After the PageSize we next assign a value to the Filter property. The Filter property is the where we define our search criteria; that’s where we tell the script exactly what to search for. We defined our filter in the first line of our code. This filter retrieves a collection of all the users in the Finance department.

7. Type $objSearcher.Filter = $strFilter, and then press ENTER.

If the search root determines the location where a search will begin, the search scope determines how much of that location will be searched.

We will assign the string Subtree to the SearchScope property. The Subtree SearchScope searches the whole subtree, including the base object and all its child objects. If the scope of a directory search is not specified, a Subtree type of search is performed.

8. Type $objSearcher.SearchScope = "Subtree", and then press ENTER.

These two lines are where we define the properties we want returned when we conduct our search. In the first line we create an array named colProplist, an array that contains each attribute we want the search to return. In this simple example we’re interested in only one attribute Name.

In the second line, we set up a foreach loop, to loop through each attribute in colProplist. For each of these attributes we call the Add method to add the attribute to the DirectorySearcher’s PropertiesToLoad property. The attributes assigned to PropertiesToLoad are the only attributes that will be

9. Type $colProplist = "name", and then press ENTER.

10. Type foreach ($i in $colPropList){$objSearcher.PropertiesToLoad.Add($i)}, and then press ENTER.

©2009 Microsoft Corporation.  All Rights Reserved 8

Page 9: Managing Web Infrastructure Systems with Windows PowerShell 2.0 Demo Script

Chapter 7 Microsoft ConfidentialChapter 8 – Microsoft Internal Use Only

returned by our search.

As soon as you’ve configured the DirectorySearcher object, actually performing a search is as easy as calling the FindAll method. Call that one method in that one line of code and your script will go out, search the requested portion of Active Directory, retrieve the requested attributes for the requested objects, and then store that information in a variable.

11. Type $colResults = $objSearcher.FindAll(), and then press ENTER.

Because the output can be a little difficult to read, we will set up a foreach loop, to loop through each record in our recordset. For each of these records we use this command to grab the returned attribute values and assign them to a variable named objItem. Then we will echo back the value of objItem’s name attribute.

12. Type foreach ($objResult in $colResults), and then press ENTER.

13. Type {$objItem = $objResult.Properties; $objItem.name}, and then press ENTER.

The result is a list of user names that are contained in the Finance OU. 14. Press ENTER.

We will perform another search of Active Directory using different code. ADSI is a Windows PowerShell Type Adapter for System.DirectoryServices.DirectoryEntry and was included in Windows PowerShell version one.

The CTP introduces a Type Adapter for using this class. $root can be set to directory entry representing an OU using ADSI if you want to restrict the scope of the search. Filter is an LDAP search string. It is also possible to use FindAll instead of FindOne to return multiple results

15. Restore PowerShellScripts.

16. Under the --- Search AD with ADSISearcher --- comment, select the text.

17. Right-click the selected text, and then click Copy.

18. Minimize PowerShellScripts.

When we run this script we see that one user account is returned. 19. Right-click the PowerShell window, and then click Paste.

20. Press ENTER.

21. Minimize Windows PowerShell V2.

Now we will move on and see how to add a domain user to a group. 22. On the desktop, double-click Active Directory Users and Computers.

23. The Active Directory Users and Computers window opens. Maximize the window.

If we look at the properties of the JEvans user we see that they are only a member of the Domain Users group.

24. In the console tree, expand Contoso.com, and then click IT.

25. In the details pane, right-click JEvans, and then click Properties.

26. The JEvans Properties dialog box appears. Click the Member Of tab.

27. Click Cancel.

This script will add the user JEvans to the Domain Admins group. First it binds the two objects we are working with, a user and a group. Then we retrieve the group members into the members variable, and then add the

28. Restore PowerShellScripts.

29. Under the --- Add Domain User to Group --- comment, select the text.

©2009 Microsoft Corporation.  All Rights Reserved 9

Page 10: Managing Web Infrastructure Systems with Windows PowerShell 2.0 Demo Script

Chapter 7 Microsoft ConfidentialChapter 8 – Microsoft Internal Use Only

full distinguished name of the object we want to include. Then we write the collection back to our group object.

30. Right-click the selected text, and then click Copy.

31. Minimize PowerShellScripts.

When we run the script there is no output verifying that the user was added to the group.

32. Restore Windows PowerShell V2.

33. Right-click the PowerShell window, and then click Paste.

34. Press ENTER.

We can go back into Active Directory Users and Computers and open the properties for the JEvans user. In the Member Of tab we can see the Domain Admins group listed.

35. Restore Active Directory Users and Computers.

36. In the details pane, right-click JEvans, and then click Properties.

37. The JEvans Properties dialog box appears. Click the Member Of tab.

38. Click Cancel.

39. Minimize Active Directory Users and Computers.

Chapter 8 Search Active Directory for Published Folders

Speaker Script StepsNow we will publish and search for published folders in Active Directory. First we will create a new folder named FinanceShare.

1. In PowerShell, type cls, and then press ENTER.

2. Type New-Item c:\FinanceShare -type directory and then press ENTER.

Next we will share the folder with this script. For simplicity we are only scripting three parameters for Win32_Share, Path, Name and Type. The value for each parameter is held by a corresponding variable, so each is easy to change.

3. Restore PowerShellScripts.

4. Under the --- Share a folder --- comment, select the text.

5. Right-click the selected text, and then click Copy.

6. Minimize PowerShellScripts.

After you run this script the FinanceShare folder is shared. 7. Right-click the PowerShell window, and then click Paste.

8. Press ENTER.

We can verify this but running this command. We see a list of all shares on the local computer.

9. In Windows PowerShell, type get-WmiObject -class Win32_Share | sort type, name and then press ENTER.

Now we want to publish our new share to Active Directory. This script will create the FinanceShare shared folder in the Finance OU. It will have a UNC name \\SEA-DC-01\FinanceShare.

10. Restore PowerShellScripts.

11. Under the --- Publish Shared folder to AD --- comment, select the text.

12. Right-click the selected text, and then click Copy.

13. Minimize PowerShellScripts.

©2009 Microsoft Corporation.  All Rights Reserved 10

Page 11: Managing Web Infrastructure Systems with Windows PowerShell 2.0 Demo Script

Chapter 7 Microsoft ConfidentialChapter 8 – Microsoft Internal Use Only

When we run this script the shared folder is published to Active Directory. 14. Right-click the PowerShell window, and then click Paste.

15. Press ENTER.

This script will search Active Directory for all published folders. 16. Restore PowerShellScripts.

17. Under the --- Search AD for Published folders --- comment, select the text.

18. Right-click the selected text, and then click Copy.

19. Minimize PowerShellScripts.

This script returns a list of the three Shared Folders we have in Active Directory, including the one we just published.

20. Right-click the PowerShell window, and then click Paste.

21. Press ENTER twice.

We can go into Active Directory Users and Computers and view the Finance OU.

22. Restore Active Directory Users and Computers.

23. Click Finance.

When we look in the Finance OU we see the new FinanceShare shared folder.

24. In the details pane, double-click FinanceShare.

25. The FinanceShare Properties dialog box appears. Click OK.

26. Close Active Directory Users and Computers.

Chapter 9 Send Us Your Feedback about This Demonstration

We appreciate hearing from you. To send your feedback, click the following link and type your comments in the message body.

Note The subject-line information is used to route your feedback. If you remove or modify the subject line we may be unable to process your feedback.

Send Feedback

©2009 Microsoft Corporation.  All Rights Reserved 11

Page 12: Managing Web Infrastructure Systems with Windows PowerShell 2.0 Demo Script

Chapter 10 Demo 2: Managing Internet Information ServicesIn this demonstration, we will use Windows PowerShell to manage IIS and create different objects such as Web Sites, Virtual Directories, and Application Pools. We will also create an FTP Site and configure Web Site properties. Finally we will see how to start and stop Web Sites user WMI.

Chapter 11 Manage Web Sites

Speaker Script StepsThe IIS 7.0 PowerShell Provider is a Windows PowerShell Snap-In that lets you manage IIS 7.0 configuration and run-time data. It gives easy access to Web-Sites, Application Pools, Web Applications, Virtual Directories, request in flight, Worker Processes and .NET Framework application Domains within Worker Processes.

Perform these steps on SEA-WEB-01.1. On the desktop, double-click IIS PowerShell Management

Console.

2. The IIS PowerShell Management Console window opens. Maximize the window.

The IIS configuration system was completely revised in version seven. The new configuration system is fully XML-based, schema-driven and completely extensible. The new IIS FTP Server and many other IIS 7.0 modules, such as the URL Rewriter, WebDAV, and others, leverage this extensibility to plug into the IIS 7.0 configuration system.

This extensibility makes it hard to ship cmdlets with static arguments. Technical Preview one of the IIS PowerShell Snap-in included only low-level cmdlets that took the total configuration extensibility in account. Every IIS configuration setting can be configured by using these cmdlets. These low-level cmdlets also work against custom configuration, for example if you extended IIS configuration with your own configuration section.

These two low-level cmdlets stop and start the default Web site and report if the site was actually stopped or started.

3. Type Stop-WebItem 'IIS:\Sites\Default Web Site' -passthru, and then press ENTER.

4. Type Start-WebItem 'IIS:\Sites\Default Web Site' -passthru, and then press ENTER.

For day-to-day IIS tasks, such as creating Web sites, enabled request tracing, adding a handler or a module, you probably want to use the task-based cmdlets that come with the IIS PowerShell Snap-in.

These two task-based cmdlets stop and start the default Web site and report if the site was actually stopped or started.

5. Type Stop-WebSite 'Default Web Site' -passthru, and then press ENTER.

6. Type Start-WebSite 'Default Web Site' -passthru, and then press ENTER.

The power of the task-based cmdlets shows when you use it for an end-to-end scenario. We will create a new web-site, add some content to the web-site, make some configuration changes, enable Request Tracing and request the new content page.

Note that you can also perform these steps by using the low-level cmdlets.

First we will create a new physical directory for our new site.

7. Type mkdir "$env:systemdrive\inetpub\MyNewWebSite", and then press ENTER.

Then we will create a new Web site called MyNewWebSite that points to the newly created directory and that listens on port 81.

8. Type New-Website -name "MyNewWebSite" -PhysicalPath "$env:systemdrive\inetpub\MyNewWebSite" -port 81, and then press ENTER.

We will navigate to the MyNewWebSite node in the IIS namespace. 9. Type cd IIS:\sites\MyNewWebsite, and then press ENTER.

©2009 Microsoft Corporation.  All Rights Reserved 12

Page 13: Managing Web Infrastructure Systems with Windows PowerShell 2.0 Demo Script

Chapter 9 Microsoft ConfidentialChapter 10 – Microsoft Internal Use Only

Now we will list all the contents of the new Web site. There is nothing to show because there is no content yet.

10. Type dir, and then press ENTER.

Now we will use this command to start Notepad and create the test.htm file. The Get-WebFilePath cmdlet gets the physical path of our IIS provider location instead of us having to remember the physical path of our web site.

11. Type notepad "$(Get-WebFilePath .)\test.htm", and then press ENTER.

12. The Notepad dialog box appears. Click Yes.

13. The Notepad window opens. Maximize the window.

We will enter some simple text in the .htm file and then save it. 14. Type Hello world and then close Notepad.

15. Click Save when you are prompted to save the changes.

Using the Get-WebURL cmdlet we will make a HTTP request to the newly created Web site and return the content we entered into notepad.

16. Type Get-WebURL ".\test.htm", and then press ENTER.

As a last step we are enabling Request Tracing. Web Request Tracing is an IIS 7.0 feature that lets you get a detailed log of what happened while a request was executing. This feature is very valuable for many troubleshooting scenarios. To enable Web Request Tracing we just have to run another location-aware cmldet called Enable-WebRequestTracing.

17. Type Enable-WebRequestTracing, and then press ENTER.

Chapter 12 Add Virtual Directories and Application Pools

Speaker Script StepsThe IIS PowerShell namespace consists of items like Web Sites, Applications, Virtual Directories and Application Pools. Creating new namespace items and managing them is very easy using the PowerShell cmdlets.

Like before we can use the low-level cmdlets or the task-based cmdlets. In this demonstration we will use the task-based cmdlets. To create the same objects by using the low-level cmdlets you would use the New-Item cmdlet.

1. Type cls, and then press ENTER.

Creating an application pool is a simple statement. You use the New-WebAppPool cmdlet and then specify the name of the application pool.

2. Type New-WebAppPool DemoAppPool, and then press ENTER.

We can create a Web application on our MyNewWebSite that uses the application pool we just created.

3. Type New-WebApplication -name DemoApp -site MyNewWebSite -PhysicalPath c:\test\DemoApp -ApplicationPool DemoAppPool, and then press ENTER.

Let's create a Virtual Directory underneath our MyNewWebSite using the New-WebVirtualDirectory cmdlet.

4. Type New-WebVirtualDirectory -site MyNewWebsite -name DemoVirtualDir1 -physicalPath c:\test\virtualDirectory1, and

©2009 Microsoft Corporation.  All Rights Reserved 13

Page 14: Managing Web Infrastructure Systems with Windows PowerShell 2.0 Demo Script

Chapter 9 Microsoft ConfidentialChapter 10 – Microsoft Internal Use Only

then press ENTER.

We will create a second one underneath the Web Application we created previously by adding the application parameter to the statement.

5. Type New-WebVirtualDirectory -site MyNewWebsite -name DemoVirtualDir2 -application DemoApp -physicalPath c:\test\virtualDirectory2, and then press ENTER.

To verify all of this we can open IIS Manager and see if the new objects are there.

6. Minimize IIS PowerShell Management Console.

7. On the desktop, double-click Internet Information Services (IIS) Manager.

8. The Internet Information Services (IIS) Manager window opens. Maximize the window.

If we look in the MyNewWebSite site we see the DemoApp Web application and the DemoVirtualDir1 virtual directory.

9. In the console tree, expand SEA-WEB-01 | Sites | MyNewWebSite.

If we then look in DemoApp we see the virtual directory that we created for the Web application.

10. In the console tree, expand DemoApp.

11. Minimize Internet Information Services (IIS) Manager.

Chapter 13 Automate Web Site Creation

Speaker Script StepsNow we will perform the same tasks using a script that is constructed to be more automated. It uses variables so that the values are easier to change. We will also use the low-level cmdlets so that we can see how the same tasks are performed with different statements.

This first section will define the variables that will be used to create our Web site.

1. On the desktop, double-click PowerShellScripts.

2. The PowerShellScripts notepad window opens. Maximize the window.

3. Under the --- New Web Site - Define Variables --- comment, select the text.

4. Right-click the selected text, and then click Copy.

5. Minimize PowerShellScripts.

This Web site will be the main Sales site for Contoso. 6. Restore the PowerShell Window.

7. Right-click the PowerShell window, and then click Paste.

8. Press ENTER.

We use the New-Item cmdlet to create four new file system directories. There is a directory for the Web Site, one for the Web application, and one for each of the virtual directories.

9. Restore PowerShellScripts.

10. Under the --- New Web Site - Create Directories --- comment, select the text.

11. Right-click the selected text, and then click Copy.

12. Minimize PowerShellScripts.

When we run this section of code the four directories are created. 13. Right-click the PowerShell window, and then click Paste.

©2009 Microsoft Corporation.  All Rights Reserved 14

Page 15: Managing Web Infrastructure Systems with Windows PowerShell 2.0 Demo Script

Chapter 9 Microsoft ConfidentialChapter 10 – Microsoft Internal Use Only

14. Press ENTER.

This code will write some simple HTML content to each of the directories we just created.

15. Restore PowerShellScripts.

16. Under the --- New Web Site - Copy Content --- comment, select the text.

17. Right-click the selected text, and then click Copy.

18. Minimize PowerShellScripts.

Let's run this code to create the new content. 19. Right-click the PowerShell window, and then click Paste.

20. Press ENTER.

This code creates the new Application Pool for the new site. 21. Restore PowerShellScripts.

22. Under the --- New Web Site - Create New Application Pool --- comment, select the text.

23. Right-click the selected text, and then click Copy.

24. Minimize PowerShellScripts.

Let's create the application pool. 25. Right-click the PowerShell window, and then click Paste.

26. Press ENTER.

This section of code creates the Web site, Web application, and two virtual directories. One virtual directory is under the Web Site and the other is under the Web application.

We are assigning the Web Site and the Web application to the application pool created previously. The Web Site is assigned to port 8080 so that it does not conflict with the 'Default Web Site'.

27. Restore PowerShellScripts.

28. Under the --- New Web Site - Create New Site --- comment, select the text.

29. Right-click the selected text, and then click Copy.

30. Minimize PowerShellScripts.

We will create the new objects now. 31. Right-click the PowerShell window, and then click Paste.

32. Press ENTER.

To verify that the script functioned properly, you could open a browser and browse to each URL. But we will use the .NET WebClient classes to request the Web content.

33. Restore PowerShellScripts.

34. Under the --- Request Web Content --- comment, select the text.

35. Right-click the selected text, and then click Copy.

36. Minimize PowerShellScripts.

The simple content we created for each directory is returned for each URL.

37. Right-click the PowerShell window, and then click Paste.

38. Press ENTER.

We can also view the new site in IIS Manager and see that it was created successfully.

39. Restore Internet Information Services (IIS) Manager.

40. In the console tree, right-click SEA-WEB-01 and then click Refresh.

41. Expand Sites | Contoso.

©2009 Microsoft Corporation.  All Rights Reserved 15

Page 16: Managing Web Infrastructure Systems with Windows PowerShell 2.0 Demo Script

Chapter 9 Microsoft ConfidentialChapter 10 – Microsoft Internal Use Only

42. Minimize Internet Information Services (IIS) Manager.

Chapter 14 Add FTP Site

Speaker Script StepsNow we will create a simple FTP site. First, we have to create a directory for our FTP site.

1. Type cls, and then press ENTER.

2. Type mkdir "$env:systemdrive\inetpub\ContosoFTP", and then press ENTER.

When we create our FTP site, we will specify the site name, port, physical path, host header, and IP address.

3. Type New-WebFtpSite -name ContosoFTP -Port 21 -PhysicalPath "$env:systemdrive\inetpub\ContosoFTP" -HostHeader ContosoFTP -IPAddress 192.168.16.2, and then press ENTER.

If we return to IIS Manager, we can see that the new FTP site was created.

4. Restore Internet Information Services (IIS) Manager.

5. In the console tree, right-click SEA-WEB-01 and then click Refresh.

6. Expand Sites, and then click ContosoFTP.

7. Minimize Internet Information Services (IIS) Manager.

We can add an FTP Authorization Rule also. We will add an allow rule for the Aaron Con user and give them read and write access.

8. Type Add-WebConfiguration "/system.ftpServer/security/authorization"  -value @{accessType="Allow";users="Acon";permissions=3} -PSPath IIS:\ -location ContosoFTP, and then press ENTER.

Again, we will use IIS Manager to confirm that the change was made. We see an authorization rule for the user ACon.

9. Restore Internet Information Services (IIS) Manager.

10. In the details pane, double-click FTP Authorization Rules.

11. Double-click ACon.

If we look at the rule we see that the user has read and write permissions. 12. The Edit Allow Authorization Rule dialog box appears. Point to Permissions.

13. Click OK.

14. Minimize Internet Information Services (IIS) Manager.

Chapter 15 Configure IIS Properties

Speaker Script StepsSometimes you might have to change Web site settings after you created 1. Type cls, and then press ENTER.

©2009 Microsoft Corporation.  All Rights Reserved 16

Page 17: Managing Web Infrastructure Systems with Windows PowerShell 2.0 Demo Script

Chapter 9 Microsoft ConfidentialChapter 10 – Microsoft Internal Use Only

them. To do this we start off using the built-in cmdlets New-ItemProperty and Set-ItemProperty. Before we start changing settings we want to look at them first. We will use the Get-Item command to look at the configuration settings of the Contoso Web site.

2. Type get-item IIS:\Sites\Contoso, and then press ENTER.

We will use the New-ItemProperty cmdlet to add an additional binding to the Contoso Web site.

3. Type New-ItemProperty IIS:\sites\Contoso -name bindings -value @{protocol="http";bindingInformation=":8081:"}, and then press ENTER.

If we run the Get-Item cmdlet again we can see that the Contoso Web site is now also listening on port 8081.

4. Press ARROW UP twice, and then press ENTER.

We can use the Set-ItemProperty cmdlet if we want to modify an existing property. For example we can change the name of the site.

5. Type Set-ItemProperty IIS:\Sites\Contoso -name name -value NewContoso, and then press ENTER.

We can see that the name was changed. 6. Type get-item IIS:\Sites\NewContoso, and then press ENTER.

Let's change it back to the original name. 7. Type Set-ItemProperty IIS:\Sites\NewContoso -name name -value Contoso, and then press ENTER.

We can also change the identity our Application Pool runs as. First we have to create a user, however.

8. Restore PowerShellScripts.

9. Under the --- Create AppPool User --- comment, select the text.

10. Right-click the selected text, and then click Copy.

11. Minimize PowerShellScripts.

Let's use ADSI to do that. 12. Right-click the PowerShell window, and then click Paste.

13. Press ENTER.

Now we are ready to configure the ContosoAppPool to run as this user. 14. Type Set-ItemProperty iis:\apppools\ContosoAppPool -name processModel -value @{userName="ContosoAppPoolUser";password="Password1";identitytype=3}, and then press ENTER.

Get-WebConfiguration and Get-WebConfigurationProperty enable you to get IIS configuration sections. They resemble Get-Item and Get-ItemProperty. Where Get-Item only works against namespace containers, Get-WebConfiguration will work against any IIS configuration section.

In this example we are using the -filter parameter to specify the configuration section we are interested in and the -name parameter to specify which property we want to look at. If you want to see the settings of a section that is not the current location, you can use the -PSPath property on top of that.

15. Type Get-WebConfigurationProperty -filter /system.webServer/directoryBrowse -name enabled -PSPath 'IIS:\Sites\Contoso', and then press ENTER.

Authentication sections are usually locked, and they can't be written to a web.config file but have to be written to the central applicationhost.config file instead. What you have to do is to use the -PSPath and -location

16. Type Set-WebConfigurationProperty -filter /system.webServer/security/authentication/windowsAuthentication -name enabled -value true -PSPath IIS:\ -location

©2009 Microsoft Corporation.  All Rights Reserved 17

Page 18: Managing Web Infrastructure Systems with Windows PowerShell 2.0 Demo Script

Chapter 9 Microsoft ConfidentialChapter 10 – Microsoft Internal Use Only

parameters. This command will enable Windows Authentication for the Web application ContosoSales. The configuration is written to applicationhost.config using a location tag.

Contoso/ContosoSales, and then press ENTER.

You don't have to specify locations when querying the configuration, however. The regular Get-WebConfigurationProperty command will show you that the setting is enabled.

17. Type Get-WebConfigurationProperty -filter /system.webServer/security/authentication/windowsAuthentication -name enabled, and then press ENTER.

Add-WebConfiguration is a cmdlet that you want to use if you have to add something to an IIS configuration collection. Handlers, modules, and default document settings are some examples in which IIS uses a collection to store multiple values.

Here is statement that adds a new default document to the Contoso Web site default document collection.

18. Type Add-WebConfiguration /system.webServer/defaultDocument/files "IIS:\sites\Contoso" -value @{value="new-index.html"}, and then press ENTER.

If we use IIS Manager we can view the default document properties for the Contoso Web site. We see that the new-index.html document was added as a default document.

19. Restore Internet Information Services (IIS) Manager.

20. In the console tree, click Contoso.

21. In the details pane, double-click Default Document.

22. Point to new-index.html.

23. Minimize Internet Information Services (IIS) Manager.

We just introduced the WebConfiguration and WebConfigurationProperty cmdlets, but there is more to these cmdlets. The -filter parameter is not just a way to specify a configuration section. It is an XPath query, and we'll see how to use a wildcard with it.

24. Type Get-WebConfigurationProperty -filter //defaultDocument/files -name Collection[value="index*"] | select value, and then press ENTER.

Now we will add an SSL binding to the Contoso Web site by using one of the task-based cmdlets called New-WebBinding.

25. Type New-WebBinding -Name "Contoso" -IP "*" -Port 443 -Protocol https, and then press ENTER.

You can also look at the binding collection using the Get-WebBinding cmdlet.

26. Type Get-WebBinding "Contoso", and then press ENTER.

Chapter 16 Use WMI to Manage Web Sites

Speaker Script StepsWe can also use WMI to manage Web Sites. We will assign the name of the site we want to manage to a variable.

1. Type cls, and then press ENTER.

2. Type $websiteName = "Contoso", and then press ENTER.

We will then use the Get-WmiObject cmdlet to retrieve the path to the Contoso Web Site in WMI and assign it to another variable. To do this, you have to know what namespace is used for IIS 7. In this case it is root/WebAdministration.

3. Type $website = Get-WmiObject -Namespace "root/WebAdministration" -Authentication 6 -ComputerName SEA-WEB-01 -Class Site | Where-Object { $_.Name -eq $websiteName }, and then press ENTER.

©2009 Microsoft Corporation.  All Rights Reserved 18

Page 19: Managing Web Infrastructure Systems with Windows PowerShell 2.0 Demo Script

Chapter 9 Microsoft ConfidentialChapter 10 – Microsoft Internal Use Only

We can write the results of our Get-WmiObject statement to the host to verify that we retrieved the information that we wanted.

4. Type Write-Host $website, and then press ENTER.

We can then use that to stop the Web Site. 5. Type $website.Stop(), and the press ENTER.

If we return to IIS Manager, we can verify that the Web site was stopped.

6. Restore Internet Information Services (IIS) Manager.

7. In the console tree, right-click SEA-WEB-01 and then click Refresh.

8. Click Sites.

9. Minimize Internet Information Services (IIS) Manager.

We can also start the Web Site again. 10. Type $website.Start(), and the press ENTER.

When we look in IIS Manager we see that the Contoso Web Site is running again.

11. Restore Internet Information Services (IIS) Manager.

12. In the console tree, right-click SEA-WEB-01 and then click Refresh.

13. Click Sites.

14. Close Internet Information Services (IIS) Manager.

15. Close IIS PowerShell Management Console.

Chapter 17 Send Us Your Feedback about This Demonstration

We appreciate hearing from you. To send your feedback, click the following link and type your comments in the message body.

Note The subject-line information is used to route your feedback. If you remove or modify the subject line we may be unable to process your feedback.

Send Feedback

©2009 Microsoft Corporation.  All Rights Reserved 19

Page 20: Managing Web Infrastructure Systems with Windows PowerShell 2.0 Demo Script

Chapter 18 Demo 3: Managing SQL ServerIn this demonstration, we will initialize the SQL Server PowerShell environment to work in Windows PowerShell version two. We will then run scripts that use WMO to retrieve and update data in SQL Server. We will use WMI to start and stop SQL Server services and finally use the Invoke-SQLcmd cmdlet to retrieve and update data in SQL Server.

Chapter 19 Initialize SQL Server PowerShell Environment

Speaker Script StepsWhen you install SQL Server 2008 you have the option of installing SQL server specific cmdlets. These are installed as part of the minishell, sqlps. The requirement for this in the SQL Server 2008 installation is Windows PowerShell version one. It will not install if you have version 2 installed.

Perform these steps on SEA-WEB-01.1. On the desktop, double-click Windows PowerShell V2.

2. The Windows PowerShell V2 window opens. Maximize the window.

The sqlps utility is a Windows PowerShell mini-shell. Mini-shells have certain restrictions. For example, they are coded to load in one or more Windows PowerShell snap-ins, but users and scripts cannot add other snap-ins. If you need functionality not supported by a mini-shell, such as working with both the SQL Server snap-ins and the snap-ins from another product, you can add the SQL Server PowerShell snap-ins directly into a Windows PowerShell environment.

3. Restore PowerShellScripts.

4. Under the --- Initialize SQL Server PowerShell Environment --- comment, select the text.

5. Right-click the selected text, and then click Copy.

6. Minimize PowerShellScripts.

The script we are running now is an example of how to do this. 7. Right-click the PowerShell window, and then click Paste.

8. Press ENTER.

Chapter 20 Work with SQL Server Management Objects

Speaker Script StepsSQL Server Management Objects (SMO) is a collection of objects that are designed for programming all aspects of managing Microsoft SQL Server. First we will show how you can create a list of all available SQL Server Instances using SMO.

Notice that the first line of our script loads an SMO assembly. When you use SMO, you have to load the appropriate SMO assembly.

1. Type cls and then press ENTER.

2. Restore PowerShellScripts.

3. Under the --- SMO - Show all SQL Servers --- comment, select the text.

4. Right-click the selected text, and then click Copy.

5. Minimize PowerShellScripts.

Because we only have the default instance installed on this server we have just one instance in our results.

6. Right-click the PowerShell window, and then click Paste.

7. Press ENTER.

The next SMO script we will run is used to create a list of all databases 8. Restore PowerShellScripts.

©2009 Microsoft Corporation.  All Rights Reserved 20

Page 21: Managing Web Infrastructure Systems with Windows PowerShell 2.0 Demo Script

on our instance of SQL Server. Notice that this script loads three SMO assemblies instead of just one.

9. Under the --- SMO - Show all Databases --- comment, select the text.

10. Right-click the selected text, and then click Copy.

11. Minimize PowerShellScripts.

When we run the script, we see a list of databases on our instance of SQL Server and the database ID for each.

12. Right-click the PowerShell window, and then click Paste.

13. Press ENTER twice.

This next script is larger than the others, so we will look at some of the different sections before we run it. This script will create a database named SMOTestDB on our instance of SQL Server.

14. Restore PowerShellScripts.

15. Point to --- SMO – Create a Database ---.

It also loads four SMO assemblies. 16. Point to # Load-SMO assemblies.

Then we'll instantiate the database object and add a file group for PRIMARY, which is required for SQL Server.

17. Point to # Instantiate a database object.

At the end of the script is the code that finally creates the database. 18. Point to # Create the new database on the server.

Now we will copy the code… 19. Under the --- SMO – Create a Database --- comment, select the text.

20. Right-click the selected text, and then click Copy.

21. Minimize PowerShellScripts.

… and then run it. We will receive a result telling us the name of the new database and the creation date.

22. Right-click the PowerShell window, and then click Paste.

23. Press ENTER.

24. Minimize Windows PowerShell V2.

Now we will open the SQL Server Management Studio and verify that the database was created on our instance of SQL Server.

25. On the desktop, double-click SQL Server Management Studio.

26. The Connect to Server dialog box appears. Click Connect.

27. The Microsoft SQL Server Management Studio window opens. Maximize the window.

We can see that the SMOTestDB database exists in the databases container.

28. In the console tree, expand Databases and then point to SMOTestDB.

This script is also somewhat large, so we will briefly examine a couple of sections. This script will create a table named SMOTable in the SMOTestDB database we just created.

29. Restore PowerShellScripts.

30. Point to --- SMO - Create a Table ---.

This section and the following Add Field sections will instantiate the table and add the field columns.

31. Point to # Instantiate a table object.

Now we will copy the code… 32. Under the --- SMO - Create a Table --- comment, select the text.

33. Right-click the selected text, and then click Copy.

34. Minimize PowerShellScripts.

… and then run it. We will receive a result telling us that the table was created.

35. Restore Windows PowerShell V2.

36. Right-click the PowerShell window, and then click Paste.

37. Press ENTER.

©2009 Microsoft Corporation.  All Rights Reserved 21

Page 22: Managing Web Infrastructure Systems with Windows PowerShell 2.0 Demo Script

38. Minimize Windows PowerShell V2.

Now we will return to SQL Server Management Studio and refresh the databases. If we look at the tables in our SMOTestDB database we can see the table we just created and the three columns.

39. In the console tree, right-click Databases and then click Refresh.

40. Expand SMOTestDB | Tables | SMOSchema.SMOTable | Columns.

41. Minimize Microsoft SQL Server Management Studio.

Chapter 21 Stop and Start Services By Using WMI

Speaker Script StepsNow we will show how to use WMI to manage SQL Server services. First we will define a variable that will hold the name of our SQL Server.

1. Restore Windows PowerShell V2.

2. Type cls, and then press ENTER.

3. Type $computer = "SEA-WEB-01", and then press ENTER.

Then we will use the Get-WMIObject cmdlet locate and stop the MSSQLSERVER service on the server. First we will try stopping the service by using the Windows service object.

4. Type (get-wmiobject win32_service -computer $computer -filter "name='MSSQLSERVER'").StopService(), and then press ENTER.

We can also use the SQL Server Computer Manager namespace to stop SQL services. We will use the SQLService class and specify the SQLBrowser service.

5. Type $namespace = “root\Microsoft\SqlServer\ComputerManagement10”, and then press ENTER.

6. Type (get-wmiobject -class SqlService -computername $computer -namespace $namespace -filter "ServiceName='SQLBrowser'").StopService(), and then press ENTER.

We will use the same statement to stop the SQL Server Agent service. 7. Type (get-wmiobject -class SqlService -computername $computer -namespace $namespace -filter "ServiceName='SQLSERVERAGENT'").StopService(), and then press ENTER.

8. Minimize Windows PowerShell V2.

We can open the SQL Server Configuration Manager to verify that these services were stopped.

9. On the desktop, double-click SQL Server Configuration Manager.

10. The SQL Server Configuration Manager window opens. Maximize the window.

11. In the console tree, click SQL Server Services.

We can start the SQL Server Browser service again. 12. In the details pane, right-click SQL Server Browser and then click Start.

We can return to Windows PowerShell and start the MSSQLSERVER service by using the Get-WMIObject cmdlet. This time we will use the Windows service object and specify StartService instead of StopService.

13. Restore Windows PowerShell V2.

14. Type (get-wmiobject win32_service -computer $computer -filter "name='MSSQLSERVER'").StartService(), and then press ENTER.

To start the SQL Server Agent service we will use the SQL Server Computer Manager namespace again and this time we will specify

15. Type (get-wmiobject win32_service -computer $computer -filter "name='SQLSERVERAGENT'").StartService(), and then

©2009 Microsoft Corporation.  All Rights Reserved 22

Page 23: Managing Web Infrastructure Systems with Windows PowerShell 2.0 Demo Script

StartService. press ENTER.

If we return to the SQL Server Configuration Manager we can see that the services are all running again.

16. Restore SQL Server Configuration Manager.

17. In the console tree, right-click SQL Server Services and then click Refresh.

18. Close SQL Server Configuration Manager.

Chapter 22 Use Invoke-SQLcmd cmdlet to Update a Table

Speaker Script StepsNow we will take a look at the Invoke-SQLcmd cmdlet. It can run a script that contains the languages and commands supported by the SQL Server sqlcmd utility. The languages supported are Transact-SQL and the XQuery syntax supported by the Database Engine. Invoke-Sqlcmd also accepts many of the commands supported by sqlcmd, such as GO and QUIT.

This first statement gets the current date and time of the SQL Server.

1. Type cls, and then press ENTER.

2. Type Invoke-SQLcmd -ServerInstance SEA-WEB-01 -Query "select @@servername as 'Server', getdate() as 'ServerTime'", and then press ENTER.

This next statement lists all databases and displays information such as the database size, owner, and the current status.

3. Type Invoke-SQLcmd -ServerInstance SEA-WEB-01 -Query "exec sp_helpdb", and then press ENTER.

This statement will get the number of blocked processes on our SQL Server.

4. Type Invoke-SQLcmd -ServerInstance SEA-WEB-01 -Query "select @@servername as 'Server', count(*) as 'Blocked' from master.dbo.sysprocesses where blocked <> 0", and then press ENTER.

We can also use the invoke-sqlcmd cmdlet to query data in a database. Here we will receive a list of products that have to be reordered because the current amount available is less than the reorder point.

5. Type invoke-sqlcmd -query "exec production.get_products_to_reorder" -database adventureworks2008 -serverinstance SEA-WEB-01, and then press ENTER.

We can navigate to different locations using the Set-Location cmdlet. We will navigate to the location of the AdventureWorks2008 database in our server instance.

6. Type set-location sqlserver:\sql\SEA-WEB-01\DEFAULT\databases\adventureworks2008, and then press ENTER.

Now we can run the command as before but this time we do not have to specify the -Database and -ServerInstance parameters.

7. Type invoke-sqlcmd -query "exec production.get_products_to_reorder", and then press ENTER.

Now we will modify an existing database by updating some rows in a table. We will update the Person.Address table in the AdventureWorks2008 database by changing the PostalCode for some of the rows. We can see what the current PostalCodes are for the first 1000 rows in the table.

8. Restore Microsoft SQL Server Management Studio.

9. In the console tree, expand AdventureWorks2008 | Tables, and then right-click Person.Address and then click Select Top 1000 Rows.

10. Point to PostalCode.

11. Minimize Microsoft SQL Server Management Studio.

We will use the Invoke-SQLcmd cmdlet to execute a query that will change the PostalCode to 98012 for any rows with a StateProvinceID of 79 and a City of Bothell.

12. Type invoke-sqlcmd -query "UPDATE Person.Address SET PostalCode= '98012' WHERE StateProvinceID = '79' AND City = 'Bothell'" -database adventureworks2008 -

©2009 Microsoft Corporation.  All Rights Reserved 23

Page 24: Managing Web Infrastructure Systems with Windows PowerShell 2.0 Demo Script

serverinstance SEA-WEB-01, and then press ENTER.

If we return to SQL Server Management Studio and select the top 1000 rows of the Person.Address table again we can see that the rows that met the criteria have had the PostalCode changed to 98012.

13. Restore Microsoft SQL Server Management Studio.

14. In the console tree, right-click Person.Address and then click Select Top 1000 Rows.

15. Point to PostalCode.

Chapter 23 Send Us Your Feedback about This Demonstration

We appreciate hearing from you. To send your feedback, click the following link and type your comments in the message body.

Note The subject-line information is used to route your feedback. If you remove or modify the subject line we may be unable to process your feedback.

Send Feedback

©2009 Microsoft Corporation.  All Rights Reserved 24