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

Level 300

Demo Script




           th
Publish...
CONTENTS

BEFORE YOU BEGIN ..................................................................................................
Before you begin
    1.   The Password for the images is Password1.
    2.   Turn on SEA-DC-01 and logon as ContosoAdminis...
Demo 1: Managing Windows Server®
In the demonstration, we will explore several ways to manage Windows Server by using Wind...
Microsoft Confidential
– Microsoft Internal Use Only
                                                                     ...
Microsoft Confidential
– Microsoft Internal Use Only
                                                                     ...
Microsoft Confidential
– Microsoft Internal Use Only
credentials of users who have permission to collect performance data....
Microsoft Confidential
– Microsoft Internal Use Only
This first sample code works equally well on both versions of Windows...
Microsoft Confidential
– Microsoft Internal Use Only
we conduct our search. In the first line we create an array named col...
Microsoft Confidential
– Microsoft Internal Use Only
member of the Domain Users group.                                    ...
Microsoft Confidential
– Microsoft Internal Use Only
After you run this script the FinanceShare folder is shared.         ...
Demo 2: Managing Internet Information Services
In this demonstration, we will use Windows PowerShell to manage IIS and cre...
Microsoft Confidential
– Microsoft Internal Use Only
                                                                     ...
Microsoft Confidential
– Microsoft Internal Use Only
                                                                     ...
Microsoft Confidential
– Microsoft Internal Use Only
one for each of the virtual directories.                             ...
Microsoft Confidential
– Microsoft Internal Use Only
The simple content we created for each directory is returned for each...
Microsoft Confidential
– Microsoft Internal Use Only
                                                                     ...
Microsoft Confidential
– Microsoft Internal Use Only
ItemProperty. Where Get-Item only works against namespace            ...
Microsoft Confidential
– Microsoft Internal Use Only
cmdlet.



Use WMI to Manage Web Sites
                           Spe...
Microsoft Confidential
– Microsoft Internal Use Only

Note The subject-line information is used to route your feedback. If...
Demo 3: Managing SQL Server
In this demonstration, we will initialize the SQL Server PowerShell environment to work in Win...
7. Press ENTER.
The next SMO script we will run is used to create a list of all databases on   8. Restore PowerShellScript...
created.                                                                36. Right-click the PowerShell window, and then cl...
Windows service object and specify StartService instead of StopService.        filter quot;name='MSSQLSERVER'quot;).StartS...
rows in the table.                                                              10. Point to PostalCode.
                 ...
Upcoming SlideShare
Loading in...5
×

Managing Web Infrastructure Systems with Windows PowerShell 2.0 Demo Script

1,389

Published on

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.

Published in: Technology
0 Comments
1 Like
Statistics
Notes
  • Be the first to comment

No Downloads
Views
Total Views
1,389
On Slideshare
0
From Embeds
0
Number of Embeds
0
Actions
Shares
0
Downloads
36
Comments
0
Likes
1
Embeds 0
No embeds

No notes for slide

Managing Web Infrastructure Systems with Windows PowerShell 2.0 Demo Script

  1. 1. SRV-300 Managing Web Infrastructure Systems with Windows PowerShell™ 2.0 Level 300 Demo Script th Published: 12 May 2009
  2. 2. 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 ........................................................................................................................................ 4 USE WMI TO MANAGE SERVERS REMOTELY .......................................................................................................................................... 5 MONITOR SERVER PERFORMANCE ...................................................................................................................................................... 6 SEARCH ACTIVE DIRECTORY FOR ACCOUNTS ......................................................................................................................................... 7 SEARCH ACTIVE DIRECTORY FOR PUBLISHED FOLDERS ............................................................................................................................ 10 SEND US YOUR FEEDBACK ABOUT THIS DEMONSTRATION ......................................................................................................................... 11 DEMO 2: MANAGING INTERNET INFORMATION SERVICES......................................................................................................................................................................................................... 12 MANAGE WEB SITES .................................................................................................................................................................... 12 ADD VIRTUAL DIRECTORIES AND APPLICATION POOLS ............................................................................................................................. 13 AUTOMATE WEB SITE CREATION ...................................................................................................................................................... 14 ADD FTP SITE ........................................................................................................................................................................... 16 CONFIGURE IIS PROPERTIES .......................................................................................................................................................... 17 USE WMI TO MANAGE WEB SITES ................................................................................................................................................... 19 SEND US YOUR FEEDBACK ABOUT THIS DEMONSTRATION ......................................................................................................................... 19 DEMO 3: MANAGING SQL SERVER ......................................................................................................................................................................................................................................................... 21 INITIALIZE SQL SERVER POWERSHELL ENVIRONMENT ............................................................................................................................. 21 WORK WITH SQL SERVER MANAGEMENT OBJECTS ................................................................................................................................. 21 STOP AND START SERVICES BY USING WMI ........................................................................................................................................ 23 USE INVOKE-SQLCMD CMDLET TO UPDATE A TABLE ............................................................................................................................... 24 SEND US YOUR FEEDBACK ABOUT THIS DEMONSTRATION ......................................................................................................................... 25 ©2009 Microsoft Corporation. All Rights Reserved 2
  3. 3. Before you begin 1. The Password for the images is Password1. 2. Turn on SEA-DC-01 and logon as ContosoAdministrator. 3. Turn on SEA-WEB-01 and logon as ContosoAdministrator. 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. 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
  4. 4. 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. Check for Hotfixes on Windows Server Speaker Script Steps Before we begin working with Windows PowerShell we will open our Windows Perform these steps on SEA-DC-01. PowerShell Scripts text file that contains code examples for some of the 1. On the desktop, double-click PowerShellScripts. longer scripts that are used during this session. 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 4. On the desktop, double-click Windows PowerShell V2. with hotfixes. 5. The Windows PowerShell V2 window opens. Maximize the window. The Get-Hotfix cmdlet gets the quick-fix engineering (QFE) updates that were 6. Type help get-hotfix and then press ENTER. applied to the local computer or to remote computers by Component-Based Servicing. To get a list of all hotfixes installed on the local computer we just have to 7. Type get-hotfix and then press ENTER. type the name of the cmdlet. This command gets the most recent hotfix on the computer. It gets the 8. Type (get-hotfix | sort installedon)[-1] and then press hotfixes, sorts them by the value of the InstalledOn property and then uses ENTER. array notation to select the last item in the array. This command gets all hotfixes on the local computer that have a description 9. Type get-hotfix -description Security*, and then press that begins with quot;Security.quot; ENTER. This command creates a text file listing the names of computers that are 10. Restore PowerShellScripts. missing a security update. The command uses the Get-Hotfix cmdlet to get 11. Under the --- Check for missing Hotfox --- comment, select the KB940518 update on all the computers whose names are listed in the the text. Servers.txt file. 12. Right-click the selected text, and then click Copy. If a computer does not have the update, the Add-Content cmdlet writes the 13. Minimize PowerShellScripts. computer name in the Missing-KB940518 text file. 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 16. Type notepad Missing-kb940518.txt, and then press ENTER. the text file we see both servers are listed which means that neither have 17. The Notepad window opens. Maximize the window. update KB940518 installed. 18. Point to the server names. ©2009 Microsoft Corporation. All Rights Reserved 4
  5. 5. Microsoft Confidential – Microsoft Internal Use Only 19. Close Notepad. Use WMI to Manage Servers Remotely Speaker Script Steps We’re going to look at a script that gets WMI information from a remote 1. Type cls, and then press ENTER. computer and uses it to create a list of all running processes on the system, 2. Type $processlist = get-wmiobject –query “select * from along with their working set sizes. win32_process” -computername SEA-WEB-01, and then First, we’ll define a variable called processlist. We’ll use the get-wmiobject press ENTER. 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, rootCIMv2. After this, we’re ready to start the For Each loop. The first line here indicates 3. Type foreach ($process in $processlist), and then press that for every process returned by the query, we’re going to perform a set of ENTER. operations. 4. Type {, and then press ENTER. We’ll create a variable that contains a single line of text that we want to write 5. Type $listitem = “Process “+$process.name+” has a to the file. This includes the process name and working set size and text to working set size of “+$process.workingsetsize, and then make the output easier to read. press ENTER. When we're done with the line of text we want to write, we’ll use the out-file 6. Type out-file –filepath “C:processworkingset-ps.txt” – command to actually write the line to the file. 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 8. Type write-host “Process Listing Complete”, and then us know when the script is finished. press ENTER. 9. Press ENTER. The text file that was created by the script has a nicely formatted list of 10. Type notepad c:processworkingset-ps.txt, and then press process names and their working set sizes, with one line for each process. 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 Perform these steps on SEA-WEB-01. Web server we will stop the Netlogon service. This will simulate a connection 14. On the desktop, double-click Services. or authentication problem on the server. 15. The Services window opens. Maximize the window. ©2009 Microsoft Corporation. All Rights Reserved 5
  6. 6. Microsoft Confidential – Microsoft Internal Use Only 16. Right-click Netlogon, and then click Stop. We can then check the state of the Netlogon service by using WMI from our Perform these steps on SEA-DC-01. domain controller. We will connect to the WMI service on the SEA-WEB-01 17. Type Get-WmiObject -computer SEA-WEB-01 computer and retrieve all instances of the Win32_Service class where the Win32_Service -Filter quot;Name='Netlogon'quot;, and then press Name property is equal to Netlogon. ENTER. We can see that the current state is Stopped. We can use the same statement to connect to the WMI service but we add 18. Type (Get-WmiObject -computer SEA-WEB-01 two things. First we add parentheses around the Get-WMIObject statement. Win32_Service -Filter This ensures that Windows PowerShell treats the returned object as an object quot;Name='Netlogon'quot;).InvokeMethod(quot;StartServicequot;,$null so that we have something we can call a method on. ), and then press ENTER. 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. We can then run our original Get-WMIObject statement to verify that the 19. Press the UP ARROW twice. service in now in a running state, which it is. 20. Press ENTER. We can also go to the Web Server and verify that the service is running in Perform these steps on SEA-WEB-01. the Services window. 21. In the Services window, click the Refresh toolbar button. 22. Point to Netlogon. 23. Close Services. Monitor Server Performance Speaker Script Steps The Get-Counter cmdlet gets live, real-time performance counter data Perform these steps on SEA-DC-01. directly from the performance monitoring instrumentation in Windows. You 1. Type cls, and then press ENTER. can use it to get performance data from the local or remote computers at the 2. Type get-help get-counter, and then press ENTER. 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 ©2009 Microsoft Corporation. All Rights Reserved 6
  7. 7. Microsoft Confidential – Microsoft Internal Use Only credentials of users who have permission to collect performance data. This command gets the current percentage of free space and total free space 3. Type Get-Counter -Counter quot;logicaldisk(c:)% Free on the SEA-WEB-01 server. We specify the performance counters by using Spacequot;,quot;logicaldisk(c:)Free Megabytesquot; -MaxSamples the Counter parameter. We also specify the computer by using the 1 -ComputerName SEA-WEB-01, and then press ENTER. ComputerName parameter. If you are not sure which counter sets are available then you can use the 4. Type Get-Counter -ListSet HTTP*, and then press ENTER. 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. You can use the Path property of a counter set to find the correctly formatted 5. Type (Get-Counter -Listset memory).paths, and then press path names for the performance counters. This command gets the path ENTER. names of the performance counters in the Memory counter set on the local computer. This command gets the current available memory and pages per second on 6. Type Get-Counter -Counter quot;MemoryAvailable the SEA-WEB-01 server. Bytesquot;,quot;MemoryPages/secquot; -MaxSamples 1 - ComputerName SEA-WEB-01, and then press ENTER. Performance counters are often protected by ACLs. To get all available performance counters, open Windows Power Shell with the quot;Run as administratorquot; option when you use Get-Counter. This command gets the current percentage of processor time combined 7. Type Get-Counter -Counter quot;Processor(_Total)% values for all processors on the local computer. It collects data every two Processor Timequot; -SampleInterval 2 -MaxSamples 3 - seconds until it has three values. ComputerName SEA-WEB-01, and then press ENTER. 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. This last command gets the current connections to the Web Service and the 8. Type Get-Counter -Counter quot;Web Service(*)Current connection attempts per second on the SEA-WEB-01 server. It collects data Connectionsquot;,quot;Web Service(*)Connection until it has two values. Attempts/secquot; -MaxSamples 2 -ComputerName SEA- WEB-01, and then press ENTER. Search Active Directory for Accounts Speaker Script Steps ©2009 Microsoft Corporation. All Rights Reserved 7
  8. 8. Microsoft Confidential – Microsoft Internal Use Only This first sample code works equally well on both versions of Windows 1. Type cls, and then press ENTER. PowerShell. There are different ways that you could perform this task but 2. Type $strFilter = here is one example. quot;(&(objectCategory=User)(Department=Finance))quot;, and First we will specify an LDAP search filter. This particular search filter then press ENTER. combines two criteria: it searches for everything that has an objectCategory equal to User and a Department equal to Finance. Now we have to identify the Active Directory location where we want the 3. Type $objDomain = New-Object search to begin. We won't specify an Active Directory location but if we System.DirectoryServices.DirectoryEntry, and then press create a DirectoryEntry object without any additional parameters we’ll ENTER. 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. After we have a DirectoryEntry object, and a starting location for our search, 4. Type $objSearcher = New-Object we will create an instance of the System.DirectoryServices.DirectorySearcher System.DirectoryServices.DirectorySearcher, and then class. This is the object that actually performs an Active Directory search. press ENTER. Before we can begin using our DirectorySearcher object we have to assign 5. Type $objSearcher.SearchRoot = $objDomain, and then values to several different properties of this object. The SearchRoot tells the press ENTER. DirectorySearcher where to begin its search. Next we assign the value 1000 to the PageSize property. By default, an 6. Type $objSearcher.PageSize = 1000, and then press Active Directory search returns only 1000 items. To have it return more items ENTER. 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. After the PageSize we next assign a value to the Filter property. The Filter 7. Type $objSearcher.Filter = $strFilter, and then press property is the where we define our search criteria; that’s where we tell the ENTER. 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. If the search root determines the location where a search will begin, the 8. Type $objSearcher.SearchScope = quot;Subtreequot;, and then search scope determines how much of that location will be searched. press ENTER. 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. These two lines are where we define the properties we want returned when 9. Type $colProplist = quot;namequot;, and then press ENTER. ©2009 Microsoft Corporation. All Rights Reserved 8
  9. 9. Microsoft Confidential – Microsoft Internal Use Only we conduct our search. In the first line we create an array named colProplist, 10. Type foreach ($i in an array that contains each attribute we want the search to return. In this $colPropList){$objSearcher.PropertiesToLoad.Add($i)}, simple example we’re interested in only one attribute Name. and then press ENTER. 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 returned by our search. As soon as you’ve configured the DirectorySearcher object, actually 11. Type $colResults = $objSearcher.FindAll(), and then press performing a search is as easy as calling the FindAll method. Call that one ENTER. 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. Because the output can be a little difficult to read, we will set up a foreach 12. Type foreach ($objResult in $colResults), and then press loop, to loop through each record in our recordset. For each of these records ENTER. we use this command to grab the returned attribute values and assign them 13. Type {$objItem = $objResult.Properties; to a variable named objItem. Then we will echo back the value of objItem’s $objItem.name}, and then press ENTER. name attribute. 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 15. Restore PowerShellScripts. is a Windows PowerShell Type Adapter for 16. Under the --- Search AD with ADSISearcher --- comment, System.DirectoryServices.DirectoryEntry and was included in Windows select the text. PowerShell version one. 17. Right-click the selected text, and then click Copy. The CTP introduces a Type Adapter for using this class. $root can be set to 18. Minimize PowerShellScripts. 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 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 24. In the console tree, expand Contoso.com, and then click IT. ©2009 Microsoft Corporation. All Rights Reserved 9
  10. 10. Microsoft Confidential – Microsoft Internal Use Only member of the Domain Users group. 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 28. Restore PowerShellScripts. binds the two objects we are working with, a user and a group. Then we 29. Under the --- Add Domain User to Group --- comment, retrieve the group members into the members variable, and then add the full select the text. distinguished name of the object we want to include. Then we write the 30. Right-click the selected text, and then click Copy. collection back to our group object. 31. Minimize PowerShellScripts. When we run the script there is no output verifying that the user was added 32. Restore Windows PowerShell V2. to the group. 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 35. Restore Active Directory Users and Computers. properties for the JEvans user. In the Member Of tab we can see the Domain 36. In the details pane, right-click JEvans, and then click Admins group listed. Properties. 37. The JEvans Properties dialog box appears. Click the Member Of tab. 38. Click Cancel. 39. Minimize Active Directory Users and Computers. Search Active Directory for Published Folders Speaker Script Steps Now we will publish and search for published folders in Active Directory. First 1. In PowerShell, type cls, and then press ENTER. we will create a new folder named FinanceShare. 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 3. Restore PowerShellScripts. scripting three parameters for Win32_Share, Path, Name and Type. The 4. Under the --- Share a folder --- comment, select the text. value for each parameter is held by a corresponding variable, so each is easy 5. Right-click the selected text, and then click Copy. to change. 6. Minimize PowerShellScripts. ©2009 Microsoft Corporation. All Rights Reserved 10
  11. 11. Microsoft Confidential – Microsoft Internal Use Only 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 9. In Windows PowerShell, type get-WmiObject -class the local computer. Win32_Share | sort type, name and then press ENTER. Now we want to publish our new share to Active Directory. This script will 10. Restore PowerShellScripts. create the FinanceShare shared folder in the Finance OU. It will have a UNC 11. Under the --- Publish Shared folder to AD --- comment, name SEA-DC-01FinanceShare. select the text. 12. Right-click the selected text, and then click Copy. 13. Minimize PowerShellScripts. 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 20. Right-click the PowerShell window, and then click Paste. Directory, including the one we just published. 21. Press ENTER twice. We can go into Active Directory Users and Computers and view the Finance 22. Restore Active Directory Users and Computers. OU. 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. 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
  12. 12. Demo 2: Managing Internet Information Services In 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. Manage Web Sites Speaker Script Steps The IIS 7.0 PowerShell Provider is a Windows PowerShell Snap-In that Perform these steps on SEA-WEB-01. lets you manage IIS 7.0 configuration and run-time data. It gives easy 1. On the desktop, double-click IIS PowerShell Management access to Web-Sites, Application Pools, Web Applications, Virtual Console. Directories, request in flight, Worker Processes and .NET Framework 2. The IIS PowerShell Management Console window opens. application Domains within Worker Processes. Maximize the window. The IIS configuration system was completely revised in version seven. 3. Type Stop-WebItem 'IIS:SitesDefault Web Site' -passthru, The new configuration system is fully XML-based, schema-driven and and then press ENTER. completely extensible. The new IIS FTP Server and many other IIS 7.0 4. Type Start-WebItem 'IIS:SitesDefault Web Site' -passthru, modules, such as the URL Rewriter, WebDAV, and others, leverage this and then press ENTER. 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. For day-to-day IIS tasks, such as creating Web sites, enabled request 5. Type Stop-WebSite 'Default Web Site' -passthru, and then tracing, adding a handler or a module, you probably want to use the press ENTER. task-based cmdlets that come with the IIS PowerShell Snap-in. 6. Type Start-WebSite 'Default Web Site' -passthru, and then These two task-based cmdlets stop and start the default Web site and press ENTER. report if the site was actually stopped or started. The power of the task-based cmdlets shows when you use it for an end- 7. Type mkdir quot;$env:systemdriveinetpubMyNewWebSitequot;, to-end scenario. We will create a new web-site, add some content to the and then press ENTER. 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. Then we will create a new Web site called MyNewWebSite that points to 8. Type New-Website -name quot;MyNewWebSitequot; -PhysicalPath the newly created directory and that listens on port 81. quot;$env:systemdriveinetpubMyNewWebSitequot; -port 81, and ©2009 Microsoft Corporation. All Rights Reserved 12
  13. 13. Microsoft Confidential – Microsoft Internal Use Only then press ENTER. We will navigate to the MyNewWebSite node in the IIS namespace. 9. Type cd IIS:sitesMyNewWebsite, and then press ENTER. Now we will list all the contents of the new Web site. There is nothing to 10. Type dir, and then press ENTER. show because there is no content yet. Now we will use this command to start Notepad and create the test.htm 11. Type notepad quot;$(Get-WebFilePath .)test.htmquot;, and then file. The Get-WebFilePath cmdlet gets the physical path of our IIS press ENTER. provider location instead of us having to remember the physical path of 12. The Notepad dialog box appears. Click Yes. our web site. 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 16. Type Get-WebURL quot;.test.htmquot;, and then press ENTER. created Web site and return the content we entered into notepad. As a last step we are enabling Request Tracing. Web Request Tracing is 17. Type Enable-WebRequestTracing, and then press ENTER. 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. Add Virtual Directories and Application Pools Speaker Script Steps The IIS PowerShell namespace consists of items like Web Sites, 1. Type cls, and then press ENTER. 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. Creating an application pool is a simple statement. You use the New- 2. Type New-WebAppPool DemoAppPool, and then press ENTER. WebAppPool cmdlet and then specify the name of the application pool. We can create a Web application on our MyNewWebSite that uses the 3. Type New-WebApplication -name DemoApp -site application pool we just created. MyNewWebSite -PhysicalPath c:testDemoApp - ©2009 Microsoft Corporation. All Rights Reserved 13
  14. 14. Microsoft Confidential – Microsoft Internal Use Only ApplicationPool DemoAppPool, and then press ENTER. Let's create a Virtual Directory underneath our MyNewWebSite using the 4. Type New-WebVirtualDirectory -site MyNewWebsite -name New-WebVirtualDirectory cmdlet. DemoVirtualDir1 -physicalPath c:testvirtualDirectory1, and then press ENTER. We will create a second one underneath the Web Application we created 5. Type New-WebVirtualDirectory -site MyNewWebsite -name previously by adding the application parameter to the statement. DemoVirtualDir2 -application DemoApp -physicalPath c:testvirtualDirectory2, and then press ENTER. To verify all of this we can open IIS Manager and see if the new objects 6. Minimize IIS PowerShell Management Console. are there. 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 9. In the console tree, expand SEA-WEB-01 | Sites | application and the DemoVirtualDir1 virtual directory. MyNewWebSite. If we then look in DemoApp we see the virtual directory that we created 10. In the console tree, expand DemoApp. for the Web application. 11. Minimize Internet Information Services (IIS) Manager. Automate Web Site Creation Speaker Script Steps Now we will perform the same tasks using a script that is constructed to 1. On the desktop, double-click PowerShellScripts. be more automated. It uses variables so that the values are easier to 2. The PowerShellScripts notepad window opens. Maximize the change. We will also use the low-level cmdlets so that we can see how window. the same tasks are performed with different statements. 3. Under the --- New Web Site - Define Variables --- comment, This first section will define the variables that will be used to create our select the text. Web site. 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. 9. Restore PowerShellScripts. There is a directory for the Web Site, one for the Web application, and 10. Under the --- New Web Site - Create Directories --- comment, ©2009 Microsoft Corporation. All Rights Reserved 14
  15. 15. Microsoft Confidential – Microsoft Internal Use Only one for each of the virtual directories. 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. 14. Press ENTER. This code will write some simple HTML content to each of the directories 15. Restore PowerShellScripts. we just created. 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 27. Restore PowerShellScripts. virtual directories. One virtual directory is under the Web Site and the 28. Under the --- New Web Site - Create New Site --- comment, other is under the Web application. select the text. We are assigning the Web Site and the Web application to the application 29. Right-click the selected text, and then click Copy. pool created previously. The Web Site is assigned to port 8080 so that it 30. Minimize PowerShellScripts. does not conflict with the 'Default Web Site'. 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 33. Restore PowerShellScripts. and browse to each URL. But we will use the .NET WebClient classes to 34. Under the --- Request Web Content --- comment, select the request the Web content. text. 35. Right-click the selected text, and then click Copy. 36. Minimize PowerShellScripts. ©2009 Microsoft Corporation. All Rights Reserved 15
  16. 16. Microsoft Confidential – Microsoft Internal Use Only The simple content we created for each directory is returned for each 37. Right-click the PowerShell window, and then click Paste. URL. 38. Press ENTER. We can also view the new site in IIS Manager and see that it was created 39. Restore Internet Information Services (IIS) Manager. successfully. 40. In the console tree, right-click SEA-WEB-01 and then click Refresh. 41. Expand Sites | Contoso. 42. Minimize Internet Information Services (IIS) Manager. Add FTP Site Speaker Script Steps Now we will create a simple FTP site. First, we have to create a directory 1. Type cls, and then press ENTER. for our FTP site. 2. Type mkdir quot;$env:systemdriveinetpubContosoFTPquot;, and then press ENTER. When we create our FTP site, we will specify the site name, port, physical 3. Type New-WebFtpSite -name ContosoFTP -Port 21 - path, host header, and IP address. PhysicalPath quot;$env:systemdriveinetpubContosoFTPquot; - 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 4. Restore Internet Information Services (IIS) Manager. created. 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 8. Type Add-WebConfiguration the Aaron Con user and give them read and write access. quot;/system.ftpServer/security/authorizationquot; -value @{accessType=quot;Allowquot;;users=quot;Aconquot;;permissions=3} - PSPath IIS: -location ContosoFTP, and then press ENTER. Again, we will use IIS Manager to confirm that the change was made. We 9. Restore Internet Information Services (IIS) Manager. see an authorization rule for the user ACon. 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 12. The Edit Allow Authorization Rule dialog box appears. Point to permissions. Permissions. ©2009 Microsoft Corporation. All Rights Reserved 16
  17. 17. Microsoft Confidential – Microsoft Internal Use Only 13. Click OK. 14. Minimize Internet Information Services (IIS) Manager. Configure IIS Properties Speaker Script Steps Sometimes you might have to change Web site settings after you created 1. Type cls, and then press ENTER. them. To do this we start off using the built-in cmdlets New-ItemProperty 2. Type get-item IIS:SitesContoso, and then press ENTER. 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. We will use the New-ItemProperty cmdlet to add an additional binding to 3. Type New-ItemProperty IIS:sitesContoso -name bindings the Contoso Web site. -value @{protocol=quot;httpquot;;bindingInformation=quot;:8081:quot;}, and then press ENTER. If we run the Get-Item cmdlet again we can see that the Contoso Web 4. Press ARROW UP twice, and then press ENTER. site is now also listening on port 8081. We can use the Set-ItemProperty cmdlet if we want to modify an existing 5. Type Set-ItemProperty IIS:SitesContoso -name name - property. For example we can change the name of the site. value NewContoso, and then press ENTER. We can see that the name was changed. 6. Type get-item IIS:SitesNewContoso, and then press ENTER. Let's change it back to the original name. 7. Type Set-ItemProperty IIS:SitesNewContoso -name name -value Contoso, and then press ENTER. We can also change the identity our Application Pool runs as. First we 8. Restore PowerShellScripts. have to create a user, however. 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:apppoolsContosoAppPool - name processModel -value @{userName=quot;ContosoAppPoolUserquot;;password=quot;Password 1quot;;identitytype=3}, and then press ENTER. Get-WebConfiguration and Get-WebConfigurationProperty enable you to 15. Type Get-WebConfigurationProperty -filter get IIS configuration sections. They resemble Get-Item and Get- /system.webServer/directoryBrowse -name enabled - ©2009 Microsoft Corporation. All Rights Reserved 17
  18. 18. Microsoft Confidential – Microsoft Internal Use Only ItemProperty. Where Get-Item only works against namespace PSPath 'IIS:SitesContoso', and then press ENTER. 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. Authentication sections are usually locked, and they can't be written to a 16. Type Set-WebConfigurationProperty -filter web.config file but have to be written to the central applicationhost.config /system.webServer/security/authentication/windowsAuthe file instead. What you have to do is to use the -PSPath and -location ntication -name enabled -value true -PSPath IIS: -location parameters. This command will enable Windows Authentication for the Contoso/ContosoSales, and then press ENTER. Web application ContosoSales. The configuration is written to applicationhost.config using a location tag. You don't have to specify locations when querying the configuration, 17. Type Get-WebConfigurationProperty -filter however. The regular Get-WebConfigurationProperty command will show /system.webServer/security/authentication/windowsAuthe you that the setting is enabled. ntication -name enabled, and then press ENTER. Add-WebConfiguration is a cmdlet that you want to use if you have to 18. Type Add-WebConfiguration add something to an IIS configuration collection. Handlers, modules, and /system.webServer/defaultDocument/files quot;IIS:sitesCon default document settings are some examples in which IIS uses a tosoquot; -value @{value=quot;new-index.htmlquot;}, and then press collection to store multiple values. ENTER. Here is statement that adds a new default document to the Contoso Web site default document collection. If we use IIS Manager we can view the default document properties for 19. Restore Internet Information Services (IIS) Manager. the Contoso Web site. We see that the new-index.html document was 20. In the console tree, click Contoso. added as a default document. 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 24. Type Get-WebConfigurationProperty -filter cmdlets, but there is more to these cmdlets. The -filter parameter is not //defaultDocument/files -name Collection[value=quot;index*quot;] just a way to specify a configuration section. It is an XPath query, and | select value, and then press ENTER. we'll see how to use a wildcard with it. Now we will add an SSL binding to the Contoso Web site by using one of 25. Type New-WebBinding -Name quot;Contosoquot; -IP quot;*quot; -Port 443 - the task-based cmdlets called New-WebBinding. Protocol https, and then press ENTER. You can also look at the binding collection using the Get-WebBinding 26. Type Get-WebBinding quot;Contosoquot;, and then press ENTER. ©2009 Microsoft Corporation. All Rights Reserved 18
  19. 19. Microsoft Confidential – Microsoft Internal Use Only cmdlet. Use WMI to Manage Web Sites Speaker Script Steps We can also use WMI to manage Web Sites. We will assign the name of 1. Type cls, and then press ENTER. the site we want to manage to a variable. 2. Type $websiteName = quot;Contosoquot;, and then press ENTER. We will then use the Get-WmiObject cmdlet to retrieve the path to the 3. Type $website = Get-WmiObject -Namespace Contoso Web Site in WMI and assign it to another variable. To do this, quot;root/WebAdministrationquot; -Authentication 6 - you have to know what namespace is used for IIS 7. In this case it is ComputerName SEA-WEB-01 -Class Site | Where-Object { root/WebAdministration. $_.Name -eq $websiteName }, and then press ENTER. We can write the results of our Get-WmiObject statement to the host to 4. Type Write-Host $website, and then press ENTER. verify that we retrieved the information that we wanted. 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 11. Restore Internet Information Services (IIS) Manager. running again. 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. 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. ©2009 Microsoft Corporation. All Rights Reserved 19
  20. 20. Microsoft Confidential – Microsoft Internal Use Only 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 20
  21. 21. Demo 3: Managing SQL Server In 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. Initialize SQL Server PowerShell Environment Speaker Script Steps When you install SQL Server 2008 you have the option of installing SQL Perform these steps on SEA-WEB-01. server specific cmdlets. These are installed as part of the minishell, sqlps. 1. On the desktop, double-click Windows PowerShell V2. The requirement for this in the SQL Server 2008 installation is Windows 2. The Windows PowerShell V2 window opens. Maximize the PowerShell version one. It will not install if you have version 2 installed. window. The sqlps utility is a Windows PowerShell mini-shell. Mini-shells have 3. Restore PowerShellScripts. certain restrictions. For example, they are coded to load in one or more 4. Under the --- Initialize SQL Server PowerShell Environment -- Windows PowerShell snap-ins, but users and scripts cannot add other - comment, select the text. snap-ins. If you need functionality not supported by a mini-shell, such as 5. Right-click the selected text, and then click Copy. working with both the SQL Server snap-ins and the snap-ins from 6. Minimize PowerShellScripts. another product, you can add the SQL Server PowerShell snap-ins directly into a Windows PowerShell environment. 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. Work with SQL Server Management Objects Speaker Script Steps SQL Server Management Objects (SMO) is a collection of objects that are 1. Type cls and then press ENTER. designed for programming all aspects of managing Microsoft SQL Server. 2. Restore PowerShellScripts. First we will show how you can create a list of all available SQL Server 3. Under the --- SMO - Show all SQL Servers --- comment, select Instances using SMO. the text. Notice that the first line of our script loads an SMO assembly. When you 4. Right-click the selected text, and then click Copy. use SMO, you have to load the appropriate SMO assembly. 5. Minimize PowerShellScripts. Because we only have the default instance installed on this server we 6. Right-click the PowerShell window, and then click Paste. have just one instance in our results. ©2009 Microsoft Corporation. All Rights Reserved 21
  22. 22. 7. Press ENTER. The next SMO script we will run is used to create a list of all databases on 8. Restore PowerShellScripts. our instance of SQL Server. Notice that this script loads three SMO 9. Under the --- SMO - Show all Databases --- comment, select the assemblies instead of just one. 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 12. Right-click the PowerShell window, and then click Paste. Server and the database ID for each. 13. Press ENTER twice. This next script is larger than the others, so we will look at some of the 14. Restore PowerShellScripts. different sections before we run it. This script will create a database 15. Point to --- SMO – Create a Database ---. named SMOTestDB on our instance of SQL Server. 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 17. Point to # Instantiate a database object. PRIMARY, which is required for SQL Server. 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 22. Right-click the PowerShell window, and then click Paste. database and the creation date. 23. Press ENTER. 24. Minimize Windows PowerShell V2. Now we will open the SQL Server Management Studio and verify that the 25. On the desktop, double-click SQL Server Management Studio. database was created on our instance of SQL Server. 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 28. In the console tree, expand Databases and then point to container. SMOTestDB. This script is also somewhat large, so we will briefly examine a couple of 29. Restore PowerShellScripts. sections. This script will create a table named SMOTable in the 30. Point to --- SMO - Create a Table ---. SMOTestDB database we just created. This section and the following Add Field sections will instantiate the table 31. Point to # Instantiate a table object. and add the field columns. 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 35. Restore Windows PowerShell V2. ©2009 Microsoft Corporation. All Rights Reserved 22
  23. 23. created. 36. Right-click the PowerShell window, and then click Paste. 37. Press ENTER. 38. Minimize Windows PowerShell V2. Now we will return to SQL Server Management Studio and refresh the 39. In the console tree, right-click Databases and then click Refresh. databases. If we look at the tables in our SMOTestDB database we can 40. Expand SMOTestDB | Tables | SMOSchema.SMOTable | see the table we just created and the three columns. Columns. 41. Minimize Microsoft SQL Server Management Studio. Stop and Start Services By Using WMI Speaker Script Steps Now we will show how to use WMI to manage SQL Server services. First 1. Restore Windows PowerShell V2. we will define a variable that will hold the name of our SQL Server. 2. Type cls, and then press ENTER. 3. Type $computer = quot;SEA-WEB-01quot;, and then press ENTER. Then we will use the Get-WMIObject cmdlet locate and stop the 4. Type (get-wmiobject win32_service -computer $computer - MSSQLSERVER service on the server. First we will try stopping the filter quot;name='MSSQLSERVER'quot;).StopService(), and then press service by using the Windows service object. ENTER. We can also use the SQL Server Computer Manager namespace to stop 5. Type $namespace = SQL services. We will use the SQLService class and specify the “rootMicrosoftSqlServerComputerManagement10”, and SQLBrowser service. then press ENTER. 6. Type (get-wmiobject -class SqlService -computername $computer -namespace $namespace -filter quot;ServiceName='SQLBrowser'quot;).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 quot;ServiceName='SQLSERVERAGENT'quot;).StopService(), and then press ENTER. 8. Minimize Windows PowerShell V2. We can open the SQL Server Configuration Manager to verify that these 9. On the desktop, double-click SQL Server Configuration services were stopped. 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 13. Restore Windows PowerShell V2. service by using the Get-WMIObject cmdlet. This time we will use the 14. Type (get-wmiobject win32_service -computer $computer - ©2009 Microsoft Corporation. All Rights Reserved 23
  24. 24. Windows service object and specify StartService instead of StopService. filter quot;name='MSSQLSERVER'quot;).StartService(), and then press ENTER. To start the SQL Server Agent service we will use the SQL Server 15. Type (get-wmiobject win32_service -computer $computer - Computer Manager namespace again and this time we will specify filter quot;name='SQLSERVERAGENT'quot;).StartService(), and then StartService. press ENTER. If we return to the SQL Server Configuration Manager we can see that 16. Restore SQL Server Configuration Manager. the services are all running again. 17. In the console tree, right-click SQL Server Services and then click Refresh. 18. Close SQL Server Configuration Manager. Use Invoke-SQLcmd cmdlet to Update a Table Speaker Script Steps Now we will take a look at the Invoke-SQLcmd cmdlet. It can run a script 1. Type cls, and then press ENTER. that contains the languages and commands supported by the SQL Server 2. Type Invoke-SQLcmd -ServerInstance SEA-WEB-01 -Query sqlcmd utility. The languages supported are Transact-SQL and the quot;select @@servername as 'Server', getdate() as XQuery syntax supported by the Database Engine. Invoke-Sqlcmd also 'ServerTime'quot;, and then press ENTER. 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. This next statement lists all databases and displays information such as 3. Type Invoke-SQLcmd -ServerInstance SEA-WEB-01 -Query the database size, owner, and the current status. quot;exec sp_helpdbquot;, and then press ENTER. This statement will get the number of blocked processes on our SQL 4. Type Invoke-SQLcmd -ServerInstance SEA-WEB-01 -Query Server. quot;select @@servername as 'Server', count(*) as 'Blocked' from master.dbo.sysprocesses where blocked <> 0quot;, and then press ENTER. We can also use the invoke-sqlcmd cmdlet to query data in a database. 5. Type invoke-sqlcmd -query quot;exec Here we will receive a list of products that have to be reordered because production.get_products_to_reorderquot; -database the current amount available is less than the reorder point. adventureworks2008 -serverinstance SEA-WEB-01, and then press ENTER. We can navigate to different locations using the Set-Location cmdlet. We 6. Type set-location sqlserver:sqlSEA-WEB- will navigate to the location of the AdventureWorks2008 database in our 01DEFAULTdatabasesadventureworks2008, and then server instance. press ENTER. Now we can run the command as before but this time we do not have to 7. Type invoke-sqlcmd -query quot;exec specify the -Database and -ServerInstance parameters. production.get_products_to_reorderquot;, and then press ENTER. Now we will modify an existing database by updating some rows in a 8. Restore Microsoft SQL Server Management Studio. table. We will update the Person.Address table in the 9. In the console tree, expand AdventureWorks2008 | Tables, and AdventureWorks2008 database by changing the PostalCode for some of then right-click Person.Address and then click Select Top 1000 the rows. We can see what the current PostalCodes are for the first 1000 Rows. ©2009 Microsoft Corporation. All Rights Reserved 24
  25. 25. rows in the table. 10. Point to PostalCode. 11. Minimize Microsoft SQL Server Management Studio. We will use the Invoke-SQLcmd cmdlet to execute a query that will 12. Type invoke-sqlcmd -query quot;UPDATE Person.Address SET change the PostalCode to 98012 for any rows with a StateProvinceID of PostalCode= '98012' WHERE StateProvinceID = '79' AND 79 and a City of Bothell. City = 'Bothell'quot; -database adventureworks2008 - serverinstance SEA-WEB-01, and then press ENTER. If we return to SQL Server Management Studio and select the top 1000 13. Restore Microsoft SQL Server Management Studio. rows of the Person.Address table again we can see that the rows that met 14. In the console tree, right-click Person.Address and then click the criteria have had the PostalCode changed to 98012. Select Top 1000 Rows. 15. Point to PostalCode. 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 25
  1. A particular slide catching your eye?

    Clipping is a handy way to collect important slides you want to go back to later.

×