SlideShare una empresa de Scribd logo
1 de 4
Descargar para leer sin conexión
Get database properties using PowerShell in SQL Server 2008 | TechRepublic



   ZDNet Asia    SmartPlanet    TechRepublic                                                                                     Log In   Join TechRepublic   FAQ   Go Pro!




                                                    Blogs     Downloads       Newsletters       Galleries      Q&A     Discussions        News
                                               Research Library


     IT Management             Development          IT Support        Data Center        Networks         Security




     Home / Blogs / The Enterprise Cloud                                                   Follow this blog:

     The Enterprise Cloud


     Get database properties using
     PowerShell in SQL Server
     2008
     By Tim Chapman
     July 7, 2010, 8:54 AM PDT

     Takeaway: Tim Chapman shows how you can use PowerShell scripts in SQL Server 2008 to
     take an inventory of database properties for SQL Server instances on your network.

     Windows PowerShell functionality is embedded in SQL Server 2008. PowerShell can be invoked
     from SQL Server Management Studio so that you can easily take advantage of its SQL Server
     functionality.

     PowerShell is great to use on SQL Server instances, but its real power is harnessed when you
     use it to administer all servers on your network. For this tutorial, I’ll write a PowerShell script that
     loops through a list of SQL Server instances that I pull from a text file; for each database on that
     instance, I will run a SQL Script to output the properties for the given database. I’ll also look at
     how to invoke SQL Server Management Objects in the example and demonstrate how easy the
     Invoke-SQL cmdlet is to use in PowerShell.

     Note: If you’re on a computer that does not have PowerShell installed, you can download the
     PowerShell environment.

     The server list
     PowerShell makes reading data from a text file and looping through its contents very easy. For our
     server list, we’ll create a new text file in Notepad (or your text editor of choice) and write SQL
     Server instances in the list. For my example, I will include two database instances: Wilma and
     WilmaR2Eval (Figure A).

     Figure A




     Save this text file to your C: drive. We’ll call it in a few minutes.




http://www.techrepublic.com/blog/datacenter/get-database-properties-using-powershell-in-sql-server-2008/2814[08/29/2012 3:56:08 PM]
Get database properties using PowerShell in SQL Server 2008 | TechRepublic


     The SQL file
     Now I will write a SQL script that will call the function DATABASEPROPERTY and several of its
     properties; this script will be called by our PowerShell script. The contents of this file are below:

     DECLARE @db SYSNAME
     SET @db = DB_NAME()
     SELECT @db AS DatabaseName, ‘IsAnsiNullDefault’ AS DBProperty,
     DATABASEPROPERTY(@db, ‘IsAnsiNullDefault’) AS Value
     UNION ALL
     SELECT @db AS DatabaseName, ‘IsAnsiNullsEnabled’, DATABASEPROPERTY(@db,
     ‘IsAnsiNullsEnabled’)
     UNION ALL
     SELECT @db AS DatabaseName, ‘IsAnsiWarningsEnabled’, DATABASEPROPERTY(@db,
     ‘IsAnsiWarningsEnabled’)
     UNION ALL
     SELECT @db AS DatabaseName, ‘IsAutoClose’, DATABASEPROPERTY(@db, ‘IsAutoClose’)
     UNION ALL
     SELECT @db AS DatabaseName, ‘IsAutoCreateStatistics’, DATABASEPROPERTY(@db,
     ‘IsAutoCreateStatistics’)
     UNION ALL
     SELECT @db AS DatabaseName, ‘IsAutoShrink’, DATABASEPROPERTY(@db, ‘IsAutoShrink’)
     UNION ALL
     SELECT @db AS DatabaseName, ‘IsAutoUpdateStatistics’, DATABASEPROPERTY(@db,
     ‘IsAutoUpdateStatistics’)
     UNION ALL
     SELECT @db AS DatabaseName, ‘IsBulkCopy’, DATABASEPROPERTY(@db, ‘IsBulkCopy’)
     UNION ALL
     SELECT @db AS DatabaseName, ‘IsCloseCursorsOnCommitEnabled’,
     DATABASEPROPERTY(@db, ‘IsCloseCursorsOnCommitEnabled’)
     UNION ALL
     SELECT @db AS DatabaseName, ‘IsDboOnly’, DATABASEPROPERTY(@db, ‘IsDboOnly’)
     UNION ALL
     SELECT @db AS DatabaseName, ‘IsDetached’, DATABASEPROPERTY(@db, ‘IsDetached’)
     UNION ALL
     SELECT @db AS DatabaseName, ‘IsEmergencyMode’, DATABASEPROPERTY(@db,
     ‘IsEmergencyMode’)
     UNION ALL
     SELECT @db AS DatabaseName, ‘IsFulltextEnabled’, DATABASEPROPERTY(@db,
     ‘IsFulltextEnabled’)
     UNION ALL
     SELECT @db AS DatabaseName, ‘IsInLoad’, DATABASEPROPERTY(@db, ‘IsInLoad’)
     UNION ALL
     SELECT @db AS DatabaseName, ‘IsInRecovery’, DATABASEPROPERTY(@db, ‘IsInRecovery’)
     UNION ALL
     SELECT @db AS DatabaseName, ‘IsInStandBy’, DATABASEPROPERTY(@db, ‘IsInStandBy’)
     UNION ALL
     SELECT @db AS DatabaseName, ‘IsLocalCursorsDefault’, DATABASEPROPERTY(@db,
     ‘IsLocalCursorsDefault’)
     UNION ALL
     SELECT @db AS DatabaseName, ‘IsNotRecovered’, DATABASEPROPERTY(@db,
     ‘IsNotRecovered’)
     UNION ALL
     SELECT @db AS DatabaseName, ‘IsNullConcat’, DATABASEPROPERTY(@db, ‘IsNullConcat’)
     UNION ALL
     SELECT @db AS DatabaseName, ‘IsOffline’, DATABASEPROPERTY(@db, ‘IsOffline’)
     UNION ALL
     SELECT @db AS DatabaseName, ‘IsParameterizationForced’, DATABASEPROPERTY(@db,
     ‘IsParameterizationForced’)
     UNION ALL
     SELECT @db AS DatabaseName, ‘IsQuotedIdentifiersEnabled’, DATABASEPROPERTY(@db,
     ‘IsQuotedIdentifiersEnabled’)
     UNION ALL
     SELECT @db AS DatabaseName, ‘IsReadOnly’, DATABASEPROPERTY(@db, ‘IsReadOnly’)



http://www.techrepublic.com/blog/datacenter/get-database-properties-using-powershell-in-sql-server-2008/2814[08/29/2012 3:56:08 PM]
Get database properties using PowerShell in SQL Server 2008 | TechRepublic


     UNION ALL
     SELECT @db AS DatabaseName,             ‘IsRecursiveTriggersEnabled’, DATABASEPROPERTY(@db,
     ‘IsRecursiveTriggersEnabled’)
     UNION ALL
     SELECT @db AS DatabaseName,             ‘IsShutDown’, DATABASEPROPERTY(@db, ‘IsShutDown’)
     UNION ALL
     SELECT @db AS DatabaseName,             ‘IsSingleUser’, DATABASEPROPERTY(@db, ‘IsSingleUser’)
     UNION ALL
     SELECT @db AS DatabaseName,             ‘IsSuspect’, DATABASEPROPERTY(@db, ‘IsSuspect’)
     UNION ALL
     SELECT @db AS DatabaseName,             ‘IsTruncLog’, DATABASEPROPERTY(@db, ‘IsTruncLog’)
     UNION ALL
     SELECT @db AS DatabaseName,             ‘Version’, DATABASEPROPERTY(@db, ‘Version’)

     Copy the script above into Notepad and save the script as DatabasePropertiesSQLScript.txt on
     your C: drive.

     PowerShell script
     Now let’s define our PowerShell script. In this script, I’ll need to invoke a SQL Server Management
     Objects (SMO) object so that I am able to loop through the databases on our SQL Server
     instances. In the first line of the script, I load the SMO assembly so I can make use of its objects.

     In the second line, I load the contents of our InstanceList.txt file into an object named $servers.
     Once I’ve loaded the object with the server list, I am able to loop through these servers using a
     foreach loop.

     In the next line, I am creating a new SMO server object and assigning it to the $sqlserver object.
     Notice that I am passing the name of the server to this function call; I am doing this so I can tell
     SMO which instance name I want my $sqlserver object to represent. Once the SMO server object
     has been defined, it exposes a Databases object, which is an enumeration of the databases
     present on the SQL Server instance. I can take advantage of the Databases property to loop
     through each of these databases on the instance.

     As I loop through each database, I call a SQL Server specific PowerShell cmdlet named invoke-
     sqlcmd. This command allows you to run a SQL Server command against a specific SQL Server
     instance and database; it also allows you to run a SQL Script from a file. This is where the SQL
     script that contains our DATABASEPROPERTY calls comes into play. I am now able to
     dynamically pass the server and database names into this command and call the SQL script for
     each database that we loop through.

     [System.Reflection.Assembly]::LoadWithPartialName(”Microsoft.SqlServer.SMO”) | Out-Null

     $servers = get-content c:InstanceList.txt

     foreach($server in $servers)
     {
     $sqlserver = new-object “Microsoft.SqlServer.Management.Smo.Server” $server
     foreach ($db in $sqlserver.Databases)
     {
     invoke-sqlcmd -inputfile c:DatabasePropertiesSQLScript.txt -database $db.name -ServerInstance
     $sqlserver.name -IgnoreProviderContext
     }
     }

     Copy the above script and paste into a text editor. Save this file to your C: drive under the name
     PSLooperScript.ps1.

     Now that all of our scripts are defined, we need to run them. To run the scripts, follow these steps:

        1. Open SQL Server Management Studio 2008.
        2. Right-click a server instance and select Start PowerShell. This opens a command-type
           window where you can enter PowerShell commands. Since we’ve defined our PowerShell
           scripts in a file, all we need to do is call the file from the interface.
        3. At the PowerShell prompt, type the location of the PowerShell script you just saved and hit



http://www.techrepublic.com/blog/datacenter/get-database-properties-using-powershell-in-sql-server-2008/2814[08/29/2012 3:56:08 PM]
Get database properties using PowerShell in SQL Server 2008 | TechRepublic

            [Enter].

     C:PSLooperScript.ps1

     If everything works properly, you’ll see a long list of databases and their properties in your
     PowerShell window.

     Summary
     In this tutorial, we used PowerShell and SMO to loop through a list of SQL Server instances from a
     text file. We then looped through each database on the SQL Server instance and ran a SQL
     Server script that output the properties for the given database.

     This simple example shows how powerful it can be to use PowerShell with SQL Server. This script
     could easily be built upon to write scripts for administering your SQL Servers, gathering instance-
     related information, and handling security or policies on your SQL Server 2008 instances.

     TechRepublic’s Servers and Storage newsletter, delivered on Monday and Wednesday, offers tips
     that will help you manage and optimize your data center. Automatically sign up today!


     Get IT Tips, news, and reviews delivered directly to your inbox by subscribing to TechRepublic’s free
     newsletters.




                   About Tim Chapman
                       Full Bio     Contact




                 Component upgrade vs.                            RAID 50 offers a balance of
                 replacement: What would                          performance, storage
                 you do?                                          capacity, and data integrity



     Join the TechRepublic Community and join the conversation! Signing-up is
     free and quick, Do it now, we want to hear your opinion.

       Join       Login




http://www.techrepublic.com/blog/datacenter/get-database-properties-using-powershell-in-sql-server-2008/2814[08/29/2012 3:56:08 PM]

Más contenido relacionado

La actualidad más candente

database-querry-student-note
database-querry-student-notedatabase-querry-student-note
database-querry-student-noteLeerpiny Makouach
 
Collaborate 2011– Leveraging and Enriching the Capabilities of Oracle Databas...
Collaborate 2011– Leveraging and Enriching the Capabilities of Oracle Databas...Collaborate 2011– Leveraging and Enriching the Capabilities of Oracle Databas...
Collaborate 2011– Leveraging and Enriching the Capabilities of Oracle Databas...djkucera
 
Running ms sql stored procedures in mule
Running ms sql stored procedures in muleRunning ms sql stored procedures in mule
Running ms sql stored procedures in muleAnilKumar Etagowni
 
Oracle Database 11g Product Family
Oracle Database 11g Product FamilyOracle Database 11g Product Family
Oracle Database 11g Product FamilyN/A
 
Playing With (B)Sqli
Playing With (B)SqliPlaying With (B)Sqli
Playing With (B)SqliChema Alonso
 
Working with Databases and MySQL
Working with Databases and MySQLWorking with Databases and MySQL
Working with Databases and MySQLNicole Ryan
 
Database Connectivity in PHP
Database Connectivity in PHPDatabase Connectivity in PHP
Database Connectivity in PHPTaha Malampatti
 
#36.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)_재직자환급교육,실업자교육,국비지원교육, 자바교육,구...
#36.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)_재직자환급교육,실업자교육,국비지원교육, 자바교육,구...#36.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)_재직자환급교육,실업자교육,국비지원교육, 자바교육,구...
#36.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)_재직자환급교육,실업자교육,국비지원교육, 자바교육,구...탑크리에듀(구로디지털단지역3번출구 2분거리)
 
Database Connection With Mysql
Database Connection With MysqlDatabase Connection With Mysql
Database Connection With MysqlHarit Kothari
 
Pluggable database tutorial 2
Pluggable database tutorial 2Pluggable database tutorial 2
Pluggable database tutorial 2Osama Mustafa
 

La actualidad más candente (20)

Mysql ppt
Mysql pptMysql ppt
Mysql ppt
 
Oracle11g notes
Oracle11g notesOracle11g notes
Oracle11g notes
 
MySql:Introduction
MySql:IntroductionMySql:Introduction
MySql:Introduction
 
Python database access
Python database accessPython database access
Python database access
 
database-querry-student-note
database-querry-student-notedatabase-querry-student-note
database-querry-student-note
 
Collaborate 2011– Leveraging and Enriching the Capabilities of Oracle Databas...
Collaborate 2011– Leveraging and Enriching the Capabilities of Oracle Databas...Collaborate 2011– Leveraging and Enriching the Capabilities of Oracle Databas...
Collaborate 2011– Leveraging and Enriching the Capabilities of Oracle Databas...
 
Mule jdbc
Mule   jdbcMule   jdbc
Mule jdbc
 
Running ms sql stored procedures in mule
Running ms sql stored procedures in muleRunning ms sql stored procedures in mule
Running ms sql stored procedures in mule
 
My sql tutorial-oscon-2012
My sql tutorial-oscon-2012My sql tutorial-oscon-2012
My sql tutorial-oscon-2012
 
Mule caching strategy with redis cache
Mule caching strategy with redis cacheMule caching strategy with redis cache
Mule caching strategy with redis cache
 
Oracle Database 11g Product Family
Oracle Database 11g Product FamilyOracle Database 11g Product Family
Oracle Database 11g Product Family
 
Playing With (B)Sqli
Playing With (B)SqliPlaying With (B)Sqli
Playing With (B)Sqli
 
Working with Databases and MySQL
Working with Databases and MySQLWorking with Databases and MySQL
Working with Databases and MySQL
 
Database Connectivity in PHP
Database Connectivity in PHPDatabase Connectivity in PHP
Database Connectivity in PHP
 
Spring introduction
Spring introductionSpring introduction
Spring introduction
 
#36.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)_재직자환급교육,실업자교육,국비지원교육, 자바교육,구...
#36.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)_재직자환급교육,실업자교육,국비지원교육, 자바교육,구...#36.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)_재직자환급교육,실업자교육,국비지원교육, 자바교육,구...
#36.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)_재직자환급교육,실업자교육,국비지원교육, 자바교육,구...
 
21 Rac
21 Rac21 Rac
21 Rac
 
Database Connection With Mysql
Database Connection With MysqlDatabase Connection With Mysql
Database Connection With Mysql
 
Pluggable database tutorial 2
Pluggable database tutorial 2Pluggable database tutorial 2
Pluggable database tutorial 2
 
Sel study notes
Sel study notesSel study notes
Sel study notes
 

Destacado

How to Create A Microsoft Access 2007 Database
How to Create A Microsoft Access 2007 DatabaseHow to Create A Microsoft Access 2007 Database
How to Create A Microsoft Access 2007 DatabaseRebecca Wright-Washington
 
Interactive spreadsheet basics[1]
Interactive spreadsheet basics[1]Interactive spreadsheet basics[1]
Interactive spreadsheet basics[1]ngoodfellow
 
Microcontroller presentation
Microcontroller presentationMicrocontroller presentation
Microcontroller presentationxavierpaulino
 
Migrate Microsoft Access to SQL Server
Migrate Microsoft Access to SQL ServerMigrate Microsoft Access to SQL Server
Migrate Microsoft Access to SQL ServerADNUG
 
Basic Access Notes
Basic Access NotesBasic Access Notes
Basic Access NotesPyi Soe
 
Introduction TO Microsoft Access
Introduction TO Microsoft AccessIntroduction TO Microsoft Access
Introduction TO Microsoft AccessChhom Karath
 
Tutorial for using SQL in Microsoft Access
Tutorial for using SQL in Microsoft AccessTutorial for using SQL in Microsoft Access
Tutorial for using SQL in Microsoft Accessmcclellm
 
PHP on Windows Training Program - New Horizons Computer Learning Center Singa...
PHP on Windows Training Program - New Horizons Computer Learning Center Singa...PHP on Windows Training Program - New Horizons Computer Learning Center Singa...
PHP on Windows Training Program - New Horizons Computer Learning Center Singa...Enterprise PHP Center
 
AIA101.2.Access Queries Accelerated
AIA101.2.Access Queries AcceleratedAIA101.2.Access Queries Accelerated
AIA101.2.Access Queries AcceleratedDan D'Urso
 
AIN102.2 Microsoft Access Queries
AIN102.2 Microsoft Access QueriesAIN102.2 Microsoft Access Queries
AIN102.2 Microsoft Access QueriesDan D'Urso
 
AIN102.1 Microsoft Access Queries Module 1
AIN102.1 Microsoft Access Queries Module 1AIN102.1 Microsoft Access Queries Module 1
AIN102.1 Microsoft Access Queries Module 1Dan D'Urso
 
pulse modulation
pulse modulation pulse modulation
pulse modulation Herin Gala
 
Database Design Slide 1
Database Design Slide 1Database Design Slide 1
Database Design Slide 1ahfiki
 
Microservices + Oracle: A Bright Future
Microservices + Oracle: A Bright FutureMicroservices + Oracle: A Bright Future
Microservices + Oracle: A Bright FutureKelly Goetsch
 
Data base management system
Data base management systemData base management system
Data base management systemNavneet Jingar
 

Destacado (20)

How to Create A Microsoft Access 2007 Database
How to Create A Microsoft Access 2007 DatabaseHow to Create A Microsoft Access 2007 Database
How to Create A Microsoft Access 2007 Database
 
Interactive spreadsheet basics[1]
Interactive spreadsheet basics[1]Interactive spreadsheet basics[1]
Interactive spreadsheet basics[1]
 
Microcontroller presentation
Microcontroller presentationMicrocontroller presentation
Microcontroller presentation
 
Migrate Microsoft Access to SQL Server
Migrate Microsoft Access to SQL ServerMigrate Microsoft Access to SQL Server
Migrate Microsoft Access to SQL Server
 
Microsoft Access
Microsoft Access Microsoft Access
Microsoft Access
 
Basic Access Notes
Basic Access NotesBasic Access Notes
Basic Access Notes
 
PWM
PWMPWM
PWM
 
Microsoft access
Microsoft accessMicrosoft access
Microsoft access
 
Introduction TO Microsoft Access
Introduction TO Microsoft AccessIntroduction TO Microsoft Access
Introduction TO Microsoft Access
 
The ABAP Query
The ABAP QueryThe ABAP Query
The ABAP Query
 
Tutorial for using SQL in Microsoft Access
Tutorial for using SQL in Microsoft AccessTutorial for using SQL in Microsoft Access
Tutorial for using SQL in Microsoft Access
 
PHP on Windows Training Program - New Horizons Computer Learning Center Singa...
PHP on Windows Training Program - New Horizons Computer Learning Center Singa...PHP on Windows Training Program - New Horizons Computer Learning Center Singa...
PHP on Windows Training Program - New Horizons Computer Learning Center Singa...
 
AIA101.2.Access Queries Accelerated
AIA101.2.Access Queries AcceleratedAIA101.2.Access Queries Accelerated
AIA101.2.Access Queries Accelerated
 
AIN102.2 Microsoft Access Queries
AIN102.2 Microsoft Access QueriesAIN102.2 Microsoft Access Queries
AIN102.2 Microsoft Access Queries
 
AIN102.1 Microsoft Access Queries Module 1
AIN102.1 Microsoft Access Queries Module 1AIN102.1 Microsoft Access Queries Module 1
AIN102.1 Microsoft Access Queries Module 1
 
pulse modulation
pulse modulation pulse modulation
pulse modulation
 
Ms access 2007
Ms access 2007Ms access 2007
Ms access 2007
 
Database Design Slide 1
Database Design Slide 1Database Design Slide 1
Database Design Slide 1
 
Microservices + Oracle: A Bright Future
Microservices + Oracle: A Bright FutureMicroservices + Oracle: A Bright Future
Microservices + Oracle: A Bright Future
 
Data base management system
Data base management systemData base management system
Data base management system
 

Similar a Get database properties using power shell in sql server 2008 techrepublic

Using object dependencies in sql server 2008 tech republic
Using object dependencies in sql server 2008   tech republicUsing object dependencies in sql server 2008   tech republic
Using object dependencies in sql server 2008 tech republicKaing Menglieng
 
Introduction to SQLite in Adobe AIR 1.5
Introduction to SQLite in Adobe AIR 1.5Introduction to SQLite in Adobe AIR 1.5
Introduction to SQLite in Adobe AIR 1.5Peter Elst
 
Sql Summit Clr, Service Broker And Xml
Sql Summit   Clr, Service Broker And XmlSql Summit   Clr, Service Broker And Xml
Sql Summit Clr, Service Broker And XmlDavid Truxall
 
resource governor
resource governorresource governor
resource governorAaron Shilo
 
SQL Track: Restoring databases with powershell
SQL Track: Restoring databases with powershellSQL Track: Restoring databases with powershell
SQL Track: Restoring databases with powershellITProceed
 
Oracle Database 12c - New Features for Developers and DBAs
Oracle Database 12c - New Features for Developers and DBAsOracle Database 12c - New Features for Developers and DBAs
Oracle Database 12c - New Features for Developers and DBAsAlex Zaballa
 
Oracle Database 12c - New Features for Developers and DBAs
Oracle Database 12c  - New Features for Developers and DBAsOracle Database 12c  - New Features for Developers and DBAs
Oracle Database 12c - New Features for Developers and DBAsAlex Zaballa
 
Asp .Net Database Connectivity Presentation.pptx
Asp .Net Database Connectivity Presentation.pptxAsp .Net Database Connectivity Presentation.pptx
Asp .Net Database Connectivity Presentation.pptxsridharu1981
 
My sql with querys
My sql with querysMy sql with querys
My sql with querysNIRMAL FELIX
 
PowerUpSQL - 2018 Blackhat USA Arsenal Presentation
PowerUpSQL - 2018 Blackhat USA Arsenal PresentationPowerUpSQL - 2018 Blackhat USA Arsenal Presentation
PowerUpSQL - 2018 Blackhat USA Arsenal PresentationScott Sutherland
 
DBMS LAB FILE1 task 1 , task 2, task3 and many more.pdf
DBMS LAB FILE1 task 1 , task 2, task3 and many more.pdfDBMS LAB FILE1 task 1 , task 2, task3 and many more.pdf
DBMS LAB FILE1 task 1 , task 2, task3 and many more.pdfAbhishekKumarPandit5
 
Introduction to Threading in .Net
Introduction to Threading in .NetIntroduction to Threading in .Net
Introduction to Threading in .Netwebhostingguy
 
How to execute an oracle stored procedure with nested table as a parameter fr...
How to execute an oracle stored procedure with nested table as a parameter fr...How to execute an oracle stored procedure with nested table as a parameter fr...
How to execute an oracle stored procedure with nested table as a parameter fr...Priyobroto Ghosh (Mule ESB Certified)
 
How to connect sql server to oracle server
How to connect sql server to oracle serverHow to connect sql server to oracle server
How to connect sql server to oracle serverGustavo Bernardo
 
Php classes in mumbai
Php classes in mumbaiPhp classes in mumbai
Php classes in mumbaiaadi Surve
 
The Ultimate Guide to Upgrade ocp java 6, 7 & 8 to java se 11 developer ...
The Ultimate Guide to Upgrade ocp java 6, 7 & 8 to java se 11 developer  ...The Ultimate Guide to Upgrade ocp java 6, 7 & 8 to java se 11 developer  ...
The Ultimate Guide to Upgrade ocp java 6, 7 & 8 to java se 11 developer ...ParshantiniRoy
 

Similar a Get database properties using power shell in sql server 2008 techrepublic (20)

Using object dependencies in sql server 2008 tech republic
Using object dependencies in sql server 2008   tech republicUsing object dependencies in sql server 2008   tech republic
Using object dependencies in sql server 2008 tech republic
 
Introduction to SQLite in Adobe AIR 1.5
Introduction to SQLite in Adobe AIR 1.5Introduction to SQLite in Adobe AIR 1.5
Introduction to SQLite in Adobe AIR 1.5
 
Sql Summit Clr, Service Broker And Xml
Sql Summit   Clr, Service Broker And XmlSql Summit   Clr, Service Broker And Xml
Sql Summit Clr, Service Broker And Xml
 
Jsp and jstl
Jsp and jstlJsp and jstl
Jsp and jstl
 
resource governor
resource governorresource governor
resource governor
 
SQL Track: Restoring databases with powershell
SQL Track: Restoring databases with powershellSQL Track: Restoring databases with powershell
SQL Track: Restoring databases with powershell
 
SQL2SPARQL
SQL2SPARQLSQL2SPARQL
SQL2SPARQL
 
Oracle Database 12c - New Features for Developers and DBAs
Oracle Database 12c - New Features for Developers and DBAsOracle Database 12c - New Features for Developers and DBAs
Oracle Database 12c - New Features for Developers and DBAs
 
Oracle Database 12c - New Features for Developers and DBAs
Oracle Database 12c  - New Features for Developers and DBAsOracle Database 12c  - New Features for Developers and DBAs
Oracle Database 12c - New Features for Developers and DBAs
 
Asp .Net Database Connectivity Presentation.pptx
Asp .Net Database Connectivity Presentation.pptxAsp .Net Database Connectivity Presentation.pptx
Asp .Net Database Connectivity Presentation.pptx
 
My sql with querys
My sql with querysMy sql with querys
My sql with querys
 
PowerUpSQL - 2018 Blackhat USA Arsenal Presentation
PowerUpSQL - 2018 Blackhat USA Arsenal PresentationPowerUpSQL - 2018 Blackhat USA Arsenal Presentation
PowerUpSQL - 2018 Blackhat USA Arsenal Presentation
 
DBMS LAB FILE1 task 1 , task 2, task3 and many more.pdf
DBMS LAB FILE1 task 1 , task 2, task3 and many more.pdfDBMS LAB FILE1 task 1 , task 2, task3 and many more.pdf
DBMS LAB FILE1 task 1 , task 2, task3 and many more.pdf
 
Introduction to Threading in .Net
Introduction to Threading in .NetIntroduction to Threading in .Net
Introduction to Threading in .Net
 
Day2
Day2Day2
Day2
 
How to execute an oracle stored procedure with nested table as a parameter fr...
How to execute an oracle stored procedure with nested table as a parameter fr...How to execute an oracle stored procedure with nested table as a parameter fr...
How to execute an oracle stored procedure with nested table as a parameter fr...
 
Android sq lite-chapter 22
Android sq lite-chapter 22Android sq lite-chapter 22
Android sq lite-chapter 22
 
How to connect sql server to oracle server
How to connect sql server to oracle serverHow to connect sql server to oracle server
How to connect sql server to oracle server
 
Php classes in mumbai
Php classes in mumbaiPhp classes in mumbai
Php classes in mumbai
 
The Ultimate Guide to Upgrade ocp java 6, 7 & 8 to java se 11 developer ...
The Ultimate Guide to Upgrade ocp java 6, 7 & 8 to java se 11 developer  ...The Ultimate Guide to Upgrade ocp java 6, 7 & 8 to java se 11 developer  ...
The Ultimate Guide to Upgrade ocp java 6, 7 & 8 to java se 11 developer ...
 

Más de Kaing Menglieng

What is your sql server backup strategy tech_republic
What is your sql server backup strategy    tech_republicWhat is your sql server backup strategy    tech_republic
What is your sql server backup strategy tech_republicKaing Menglieng
 
Using sql server 2008's merge statement tech republic
Using sql server 2008's merge statement   tech republicUsing sql server 2008's merge statement   tech republic
Using sql server 2008's merge statement tech republicKaing Menglieng
 
Using hash fields in sql server tech republic
Using hash fields in sql server   tech republicUsing hash fields in sql server   tech republic
Using hash fields in sql server tech republicKaing Menglieng
 
Using grouping sets in sql server 2008 tech republic
Using grouping sets in sql server 2008   tech republicUsing grouping sets in sql server 2008   tech republic
Using grouping sets in sql server 2008 tech republicKaing Menglieng
 
Understand when to use user defined functions in sql server tech-republic
Understand when to use user defined functions in sql server   tech-republicUnderstand when to use user defined functions in sql server   tech-republic
Understand when to use user defined functions in sql server tech-republicKaing Menglieng
 
Sql server indexed views speed up your select queries part 1 - code-projec
Sql server indexed views   speed up your select queries  part 1 - code-projecSql server indexed views   speed up your select queries  part 1 - code-projec
Sql server indexed views speed up your select queries part 1 - code-projecKaing Menglieng
 
Sql server – query optimization – remove bookmark lookup – remove rid lookup
Sql server – query optimization – remove bookmark lookup – remove rid lookupSql server – query optimization – remove bookmark lookup – remove rid lookup
Sql server – query optimization – remove bookmark lookup – remove rid lookupKaing Menglieng
 
Sql server common interview questions and answers
Sql server   common interview questions and answersSql server   common interview questions and answers
Sql server common interview questions and answersKaing Menglieng
 
Sql server common interview questions and answers page 6
Sql server   common interview questions and answers page 6Sql server   common interview questions and answers page 6
Sql server common interview questions and answers page 6Kaing Menglieng
 
Sql server common interview questions and answers page 5
Sql server   common interview questions and answers page 5Sql server   common interview questions and answers page 5
Sql server common interview questions and answers page 5Kaing Menglieng
 
Sql server common interview questions and answers page 4
Sql server   common interview questions and answers page 4Sql server   common interview questions and answers page 4
Sql server common interview questions and answers page 4Kaing Menglieng
 
Sql server common interview questions and answers page 2
Sql server   common interview questions and answers page 2Sql server   common interview questions and answers page 2
Sql server common interview questions and answers page 2Kaing Menglieng
 
Sql server – 2008 – hardware and software requirements for installing sql se
Sql server – 2008 – hardware and software requirements for installing sql seSql server – 2008 – hardware and software requirements for installing sql se
Sql server – 2008 – hardware and software requirements for installing sql seKaing Menglieng
 
Speeding up queries with semi joins and anti-joins
Speeding up queries with semi joins and anti-joinsSpeeding up queries with semi joins and anti-joins
Speeding up queries with semi joins and anti-joinsKaing Menglieng
 
Speed up sql server apps - visual studio magazine
Speed up sql server apps  - visual studio magazineSpeed up sql server apps  - visual studio magazine
Speed up sql server apps - visual studio magazineKaing Menglieng
 
See sql server graphical execution plans in action tech republic
See sql server graphical execution plans in action   tech republicSee sql server graphical execution plans in action   tech republic
See sql server graphical execution plans in action tech republicKaing Menglieng
 
Reviewing sql server permissions tech republic
Reviewing sql server permissions   tech republicReviewing sql server permissions   tech republic
Reviewing sql server permissions tech republicKaing Menglieng
 
Query optimization how to search millions of record in sql table faster -
Query optimization   how to search millions of record in sql table faster  -Query optimization   how to search millions of record in sql table faster  -
Query optimization how to search millions of record in sql table faster -Kaing Menglieng
 
Optimize sql server queries with these advanced tuning techniques tech repu
Optimize sql server queries with these advanced tuning techniques   tech repuOptimize sql server queries with these advanced tuning techniques   tech repu
Optimize sql server queries with these advanced tuning techniques tech repuKaing Menglieng
 

Más de Kaing Menglieng (20)

What is your sql server backup strategy tech_republic
What is your sql server backup strategy    tech_republicWhat is your sql server backup strategy    tech_republic
What is your sql server backup strategy tech_republic
 
Using sql server 2008's merge statement tech republic
Using sql server 2008's merge statement   tech republicUsing sql server 2008's merge statement   tech republic
Using sql server 2008's merge statement tech republic
 
Using hash fields in sql server tech republic
Using hash fields in sql server   tech republicUsing hash fields in sql server   tech republic
Using hash fields in sql server tech republic
 
Using grouping sets in sql server 2008 tech republic
Using grouping sets in sql server 2008   tech republicUsing grouping sets in sql server 2008   tech republic
Using grouping sets in sql server 2008 tech republic
 
Understand when to use user defined functions in sql server tech-republic
Understand when to use user defined functions in sql server   tech-republicUnderstand when to use user defined functions in sql server   tech-republic
Understand when to use user defined functions in sql server tech-republic
 
Sql server indexed views speed up your select queries part 1 - code-projec
Sql server indexed views   speed up your select queries  part 1 - code-projecSql server indexed views   speed up your select queries  part 1 - code-projec
Sql server indexed views speed up your select queries part 1 - code-projec
 
Sql server – query optimization – remove bookmark lookup – remove rid lookup
Sql server – query optimization – remove bookmark lookup – remove rid lookupSql server – query optimization – remove bookmark lookup – remove rid lookup
Sql server – query optimization – remove bookmark lookup – remove rid lookup
 
Sql server common interview questions and answers
Sql server   common interview questions and answersSql server   common interview questions and answers
Sql server common interview questions and answers
 
Sql server common interview questions and answers page 6
Sql server   common interview questions and answers page 6Sql server   common interview questions and answers page 6
Sql server common interview questions and answers page 6
 
Sql server common interview questions and answers page 5
Sql server   common interview questions and answers page 5Sql server   common interview questions and answers page 5
Sql server common interview questions and answers page 5
 
Sql server common interview questions and answers page 4
Sql server   common interview questions and answers page 4Sql server   common interview questions and answers page 4
Sql server common interview questions and answers page 4
 
Sql server common interview questions and answers page 2
Sql server   common interview questions and answers page 2Sql server   common interview questions and answers page 2
Sql server common interview questions and answers page 2
 
Sql server – 2008 – hardware and software requirements for installing sql se
Sql server – 2008 – hardware and software requirements for installing sql seSql server – 2008 – hardware and software requirements for installing sql se
Sql server – 2008 – hardware and software requirements for installing sql se
 
Speeding up queries with semi joins and anti-joins
Speeding up queries with semi joins and anti-joinsSpeeding up queries with semi joins and anti-joins
Speeding up queries with semi joins and anti-joins
 
Speed up sql
Speed up sqlSpeed up sql
Speed up sql
 
Speed up sql server apps - visual studio magazine
Speed up sql server apps  - visual studio magazineSpeed up sql server apps  - visual studio magazine
Speed up sql server apps - visual studio magazine
 
See sql server graphical execution plans in action tech republic
See sql server graphical execution plans in action   tech republicSee sql server graphical execution plans in action   tech republic
See sql server graphical execution plans in action tech republic
 
Reviewing sql server permissions tech republic
Reviewing sql server permissions   tech republicReviewing sql server permissions   tech republic
Reviewing sql server permissions tech republic
 
Query optimization how to search millions of record in sql table faster -
Query optimization   how to search millions of record in sql table faster  -Query optimization   how to search millions of record in sql table faster  -
Query optimization how to search millions of record in sql table faster -
 
Optimize sql server queries with these advanced tuning techniques tech repu
Optimize sql server queries with these advanced tuning techniques   tech repuOptimize sql server queries with these advanced tuning techniques   tech repu
Optimize sql server queries with these advanced tuning techniques tech repu
 

Get database properties using power shell in sql server 2008 techrepublic

  • 1. Get database properties using PowerShell in SQL Server 2008 | TechRepublic ZDNet Asia SmartPlanet TechRepublic Log In Join TechRepublic FAQ Go Pro! Blogs Downloads Newsletters Galleries Q&A Discussions News Research Library IT Management Development IT Support Data Center Networks Security Home / Blogs / The Enterprise Cloud Follow this blog: The Enterprise Cloud Get database properties using PowerShell in SQL Server 2008 By Tim Chapman July 7, 2010, 8:54 AM PDT Takeaway: Tim Chapman shows how you can use PowerShell scripts in SQL Server 2008 to take an inventory of database properties for SQL Server instances on your network. Windows PowerShell functionality is embedded in SQL Server 2008. PowerShell can be invoked from SQL Server Management Studio so that you can easily take advantage of its SQL Server functionality. PowerShell is great to use on SQL Server instances, but its real power is harnessed when you use it to administer all servers on your network. For this tutorial, I’ll write a PowerShell script that loops through a list of SQL Server instances that I pull from a text file; for each database on that instance, I will run a SQL Script to output the properties for the given database. I’ll also look at how to invoke SQL Server Management Objects in the example and demonstrate how easy the Invoke-SQL cmdlet is to use in PowerShell. Note: If you’re on a computer that does not have PowerShell installed, you can download the PowerShell environment. The server list PowerShell makes reading data from a text file and looping through its contents very easy. For our server list, we’ll create a new text file in Notepad (or your text editor of choice) and write SQL Server instances in the list. For my example, I will include two database instances: Wilma and WilmaR2Eval (Figure A). Figure A Save this text file to your C: drive. We’ll call it in a few minutes. http://www.techrepublic.com/blog/datacenter/get-database-properties-using-powershell-in-sql-server-2008/2814[08/29/2012 3:56:08 PM]
  • 2. Get database properties using PowerShell in SQL Server 2008 | TechRepublic The SQL file Now I will write a SQL script that will call the function DATABASEPROPERTY and several of its properties; this script will be called by our PowerShell script. The contents of this file are below: DECLARE @db SYSNAME SET @db = DB_NAME() SELECT @db AS DatabaseName, ‘IsAnsiNullDefault’ AS DBProperty, DATABASEPROPERTY(@db, ‘IsAnsiNullDefault’) AS Value UNION ALL SELECT @db AS DatabaseName, ‘IsAnsiNullsEnabled’, DATABASEPROPERTY(@db, ‘IsAnsiNullsEnabled’) UNION ALL SELECT @db AS DatabaseName, ‘IsAnsiWarningsEnabled’, DATABASEPROPERTY(@db, ‘IsAnsiWarningsEnabled’) UNION ALL SELECT @db AS DatabaseName, ‘IsAutoClose’, DATABASEPROPERTY(@db, ‘IsAutoClose’) UNION ALL SELECT @db AS DatabaseName, ‘IsAutoCreateStatistics’, DATABASEPROPERTY(@db, ‘IsAutoCreateStatistics’) UNION ALL SELECT @db AS DatabaseName, ‘IsAutoShrink’, DATABASEPROPERTY(@db, ‘IsAutoShrink’) UNION ALL SELECT @db AS DatabaseName, ‘IsAutoUpdateStatistics’, DATABASEPROPERTY(@db, ‘IsAutoUpdateStatistics’) UNION ALL SELECT @db AS DatabaseName, ‘IsBulkCopy’, DATABASEPROPERTY(@db, ‘IsBulkCopy’) UNION ALL SELECT @db AS DatabaseName, ‘IsCloseCursorsOnCommitEnabled’, DATABASEPROPERTY(@db, ‘IsCloseCursorsOnCommitEnabled’) UNION ALL SELECT @db AS DatabaseName, ‘IsDboOnly’, DATABASEPROPERTY(@db, ‘IsDboOnly’) UNION ALL SELECT @db AS DatabaseName, ‘IsDetached’, DATABASEPROPERTY(@db, ‘IsDetached’) UNION ALL SELECT @db AS DatabaseName, ‘IsEmergencyMode’, DATABASEPROPERTY(@db, ‘IsEmergencyMode’) UNION ALL SELECT @db AS DatabaseName, ‘IsFulltextEnabled’, DATABASEPROPERTY(@db, ‘IsFulltextEnabled’) UNION ALL SELECT @db AS DatabaseName, ‘IsInLoad’, DATABASEPROPERTY(@db, ‘IsInLoad’) UNION ALL SELECT @db AS DatabaseName, ‘IsInRecovery’, DATABASEPROPERTY(@db, ‘IsInRecovery’) UNION ALL SELECT @db AS DatabaseName, ‘IsInStandBy’, DATABASEPROPERTY(@db, ‘IsInStandBy’) UNION ALL SELECT @db AS DatabaseName, ‘IsLocalCursorsDefault’, DATABASEPROPERTY(@db, ‘IsLocalCursorsDefault’) UNION ALL SELECT @db AS DatabaseName, ‘IsNotRecovered’, DATABASEPROPERTY(@db, ‘IsNotRecovered’) UNION ALL SELECT @db AS DatabaseName, ‘IsNullConcat’, DATABASEPROPERTY(@db, ‘IsNullConcat’) UNION ALL SELECT @db AS DatabaseName, ‘IsOffline’, DATABASEPROPERTY(@db, ‘IsOffline’) UNION ALL SELECT @db AS DatabaseName, ‘IsParameterizationForced’, DATABASEPROPERTY(@db, ‘IsParameterizationForced’) UNION ALL SELECT @db AS DatabaseName, ‘IsQuotedIdentifiersEnabled’, DATABASEPROPERTY(@db, ‘IsQuotedIdentifiersEnabled’) UNION ALL SELECT @db AS DatabaseName, ‘IsReadOnly’, DATABASEPROPERTY(@db, ‘IsReadOnly’) http://www.techrepublic.com/blog/datacenter/get-database-properties-using-powershell-in-sql-server-2008/2814[08/29/2012 3:56:08 PM]
  • 3. Get database properties using PowerShell in SQL Server 2008 | TechRepublic UNION ALL SELECT @db AS DatabaseName, ‘IsRecursiveTriggersEnabled’, DATABASEPROPERTY(@db, ‘IsRecursiveTriggersEnabled’) UNION ALL SELECT @db AS DatabaseName, ‘IsShutDown’, DATABASEPROPERTY(@db, ‘IsShutDown’) UNION ALL SELECT @db AS DatabaseName, ‘IsSingleUser’, DATABASEPROPERTY(@db, ‘IsSingleUser’) UNION ALL SELECT @db AS DatabaseName, ‘IsSuspect’, DATABASEPROPERTY(@db, ‘IsSuspect’) UNION ALL SELECT @db AS DatabaseName, ‘IsTruncLog’, DATABASEPROPERTY(@db, ‘IsTruncLog’) UNION ALL SELECT @db AS DatabaseName, ‘Version’, DATABASEPROPERTY(@db, ‘Version’) Copy the script above into Notepad and save the script as DatabasePropertiesSQLScript.txt on your C: drive. PowerShell script Now let’s define our PowerShell script. In this script, I’ll need to invoke a SQL Server Management Objects (SMO) object so that I am able to loop through the databases on our SQL Server instances. In the first line of the script, I load the SMO assembly so I can make use of its objects. In the second line, I load the contents of our InstanceList.txt file into an object named $servers. Once I’ve loaded the object with the server list, I am able to loop through these servers using a foreach loop. In the next line, I am creating a new SMO server object and assigning it to the $sqlserver object. Notice that I am passing the name of the server to this function call; I am doing this so I can tell SMO which instance name I want my $sqlserver object to represent. Once the SMO server object has been defined, it exposes a Databases object, which is an enumeration of the databases present on the SQL Server instance. I can take advantage of the Databases property to loop through each of these databases on the instance. As I loop through each database, I call a SQL Server specific PowerShell cmdlet named invoke- sqlcmd. This command allows you to run a SQL Server command against a specific SQL Server instance and database; it also allows you to run a SQL Script from a file. This is where the SQL script that contains our DATABASEPROPERTY calls comes into play. I am now able to dynamically pass the server and database names into this command and call the SQL script for each database that we loop through. [System.Reflection.Assembly]::LoadWithPartialName(”Microsoft.SqlServer.SMO”) | Out-Null $servers = get-content c:InstanceList.txt foreach($server in $servers) { $sqlserver = new-object “Microsoft.SqlServer.Management.Smo.Server” $server foreach ($db in $sqlserver.Databases) { invoke-sqlcmd -inputfile c:DatabasePropertiesSQLScript.txt -database $db.name -ServerInstance $sqlserver.name -IgnoreProviderContext } } Copy the above script and paste into a text editor. Save this file to your C: drive under the name PSLooperScript.ps1. Now that all of our scripts are defined, we need to run them. To run the scripts, follow these steps: 1. Open SQL Server Management Studio 2008. 2. Right-click a server instance and select Start PowerShell. This opens a command-type window where you can enter PowerShell commands. Since we’ve defined our PowerShell scripts in a file, all we need to do is call the file from the interface. 3. At the PowerShell prompt, type the location of the PowerShell script you just saved and hit http://www.techrepublic.com/blog/datacenter/get-database-properties-using-powershell-in-sql-server-2008/2814[08/29/2012 3:56:08 PM]
  • 4. Get database properties using PowerShell in SQL Server 2008 | TechRepublic [Enter]. C:PSLooperScript.ps1 If everything works properly, you’ll see a long list of databases and their properties in your PowerShell window. Summary In this tutorial, we used PowerShell and SMO to loop through a list of SQL Server instances from a text file. We then looped through each database on the SQL Server instance and ran a SQL Server script that output the properties for the given database. This simple example shows how powerful it can be to use PowerShell with SQL Server. This script could easily be built upon to write scripts for administering your SQL Servers, gathering instance- related information, and handling security or policies on your SQL Server 2008 instances. TechRepublic’s Servers and Storage newsletter, delivered on Monday and Wednesday, offers tips that will help you manage and optimize your data center. Automatically sign up today! Get IT Tips, news, and reviews delivered directly to your inbox by subscribing to TechRepublic’s free newsletters. About Tim Chapman Full Bio Contact Component upgrade vs. RAID 50 offers a balance of replacement: What would performance, storage you do? capacity, and data integrity Join the TechRepublic Community and join the conversation! Signing-up is free and quick, Do it now, we want to hear your opinion. Join Login http://www.techrepublic.com/blog/datacenter/get-database-properties-using-powershell-in-sql-server-2008/2814[08/29/2012 3:56:08 PM]