SlideShare a Scribd company logo
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]

More Related Content

What's hot (20)

PPT
Mysql ppt
Sanmuga Nathan
 
TXT
Oracle11g notes
Manish Mudhliyar
 
PPTX
MySql:Introduction
DataminingTools Inc
 
DOCX
database-querry-student-note
Leerpiny Makouach
 
PPT
Collaborate 2011– Leveraging and Enriching the Capabilities of Oracle Databas...
djkucera
 
PPTX
Mule jdbc
KalaimathiS
 
ODP
Running ms sql stored procedures in mule
AnilKumar Etagowni
 
PDF
My sql tutorial-oscon-2012
John David Duncan
 
PDF
Mule caching strategy with redis cache
Priyobroto Ghosh (Mule ESB Certified)
 
PDF
Oracle Database 11g Product Family
N/A
 
PPTX
Playing With (B)Sqli
Chema Alonso
 
PPT
Working with Databases and MySQL
Nicole Ryan
 
PPTX
Database Connectivity in PHP
Taha Malampatti
 
PPT
Spring introduction
AnilKumar Etagowni
 
PDF
#36.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)_재직자환급교육,실업자교육,국비지원교육, 자바교육,구...
탑크리에듀(구로디지털단지역3번출구 2분거리)
 
PDF
21 Rac
Emanuel Mateus
 
ODP
Database Connection With Mysql
Harit Kothari
 
PDF
Pluggable database tutorial 2
Osama Mustafa
 
DOC
Sel study notes
Lalit Singh
 
Mysql ppt
Sanmuga Nathan
 
Oracle11g notes
Manish Mudhliyar
 
MySql:Introduction
DataminingTools Inc
 
database-querry-student-note
Leerpiny Makouach
 
Collaborate 2011– Leveraging and Enriching the Capabilities of Oracle Databas...
djkucera
 
Mule jdbc
KalaimathiS
 
Running ms sql stored procedures in mule
AnilKumar Etagowni
 
My sql tutorial-oscon-2012
John David Duncan
 
Mule caching strategy with redis cache
Priyobroto Ghosh (Mule ESB Certified)
 
Oracle Database 11g Product Family
N/A
 
Playing With (B)Sqli
Chema Alonso
 
Working with Databases and MySQL
Nicole Ryan
 
Database Connectivity in PHP
Taha Malampatti
 
Spring introduction
AnilKumar Etagowni
 
#36.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)_재직자환급교육,실업자교육,국비지원교육, 자바교육,구...
탑크리에듀(구로디지털단지역3번출구 2분거리)
 
Database Connection With Mysql
Harit Kothari
 
Pluggable database tutorial 2
Osama Mustafa
 
Sel study notes
Lalit Singh
 

Viewers also liked (20)

PPTX
How to Create A Microsoft Access 2007 Database
Rebecca Wright-Washington
 
PPT
Interactive spreadsheet basics[1]
ngoodfellow
 
PPTX
Microcontroller presentation
xavierpaulino
 
PPT
Migrate Microsoft Access to SQL Server
ADNUG
 
PDF
Microsoft Access
Anabel Condor
 
PDF
Basic Access Notes
Pyi Soe
 
DOCX
PWM
mulluraniket
 
PPTX
Microsoft access
Pedro Espinosa
 
PPTX
Introduction TO Microsoft Access
Chhom Karath
 
PPT
The ABAP Query
PeterHBrown
 
PPTX
Tutorial for using SQL in Microsoft Access
mcclellm
 
PPT
PHP on Windows Training Program - New Horizons Computer Learning Center Singa...
Enterprise PHP Center
 
PPT
AIA101.2.Access Queries Accelerated
Dan D'Urso
 
PPT
AIN102.2 Microsoft Access Queries
Dan D'Urso
 
PPT
AIN102.1 Microsoft Access Queries Module 1
Dan D'Urso
 
PPTX
pulse modulation
Herin Gala
 
PPTX
Ms access 2007
Ramesh Pant
 
PPS
Database Design Slide 1
ahfiki
 
PPTX
Microservices + Oracle: A Bright Future
Kelly Goetsch
 
PPTX
Data base management system
Navneet Jingar
 
How to Create A Microsoft Access 2007 Database
Rebecca Wright-Washington
 
Interactive spreadsheet basics[1]
ngoodfellow
 
Microcontroller presentation
xavierpaulino
 
Migrate Microsoft Access to SQL Server
ADNUG
 
Microsoft Access
Anabel Condor
 
Basic Access Notes
Pyi Soe
 
Microsoft access
Pedro Espinosa
 
Introduction TO Microsoft Access
Chhom Karath
 
The ABAP Query
PeterHBrown
 
Tutorial for using SQL in Microsoft Access
mcclellm
 
PHP on Windows Training Program - New Horizons Computer Learning Center Singa...
Enterprise PHP Center
 
AIA101.2.Access Queries Accelerated
Dan D'Urso
 
AIN102.2 Microsoft Access Queries
Dan D'Urso
 
AIN102.1 Microsoft Access Queries Module 1
Dan D'Urso
 
pulse modulation
Herin Gala
 
Ms access 2007
Ramesh Pant
 
Database Design Slide 1
ahfiki
 
Microservices + Oracle: A Bright Future
Kelly Goetsch
 
Data base management system
Navneet Jingar
 
Ad

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

PPSX
Demo for Why Use PowerShell
SirajJamdar
 
PDF
SQL Track: Restoring databases with powershell
ITProceed
 
PPTX
My first powershell script
David Cobb
 
PDF
Reviewing sql server permissions tech republic
Kaing Menglieng
 
PPTX
MSSQL SERVER
Dharmendrasingh417
 
PPTX
Sql Automation 20090610
livingco
 
PPTX
6232 b 01
stamal
 
PPT
SQL Server Basics Hello world iam here.ppt
nanisaketh
 
PPTX
Query Analyser , SQL Server Groups, Transact –SQL
Komal Batra
 
PPTX
10 SQL Server Metrics to Monitor
SQLDBApros
 
PDF
Selje_SSMS for the Accidental DBA.pdf
Eric Selje
 
PDF
SSIS 2012: Parameters vs. Configurations
Allen Smith
 
PPTX
Monitoring Microsoft SQL Server 2008 with Opsview
Opsview
 
PPT
Sql server basics
Dilfaroz Khan
 
PPTX
2017 OWASP SanFran March Meetup - Hacking SQL Server on Scale with PowerShell
Scott Sutherland
 
PPTX
SQL 2012 and Powershell for the Bleeding Edge DBA
dpcobb
 
PPTX
Sql saturday oc 2019
SitotpalSarkar
 
PDF
Microsoft SQL Server 2008 Administration with Windows PowerShell 1st Edition ...
yadiniraies
 
PPTX
PowerShellForDBDevelopers
Bryan Cafferky
 
PPTX
2017 Secure360 - Hacking SQL Server on Scale with PowerShell
Scott Sutherland
 
Demo for Why Use PowerShell
SirajJamdar
 
SQL Track: Restoring databases with powershell
ITProceed
 
My first powershell script
David Cobb
 
Reviewing sql server permissions tech republic
Kaing Menglieng
 
MSSQL SERVER
Dharmendrasingh417
 
Sql Automation 20090610
livingco
 
6232 b 01
stamal
 
SQL Server Basics Hello world iam here.ppt
nanisaketh
 
Query Analyser , SQL Server Groups, Transact –SQL
Komal Batra
 
10 SQL Server Metrics to Monitor
SQLDBApros
 
Selje_SSMS for the Accidental DBA.pdf
Eric Selje
 
SSIS 2012: Parameters vs. Configurations
Allen Smith
 
Monitoring Microsoft SQL Server 2008 with Opsview
Opsview
 
Sql server basics
Dilfaroz Khan
 
2017 OWASP SanFran March Meetup - Hacking SQL Server on Scale with PowerShell
Scott Sutherland
 
SQL 2012 and Powershell for the Bleeding Edge DBA
dpcobb
 
Sql saturday oc 2019
SitotpalSarkar
 
Microsoft SQL Server 2008 Administration with Windows PowerShell 1st Edition ...
yadiniraies
 
PowerShellForDBDevelopers
Bryan Cafferky
 
2017 Secure360 - Hacking SQL Server on Scale with PowerShell
Scott Sutherland
 
Ad

More from Kaing Menglieng (20)

PDF
What is your sql server backup strategy tech_republic
Kaing Menglieng
 
PDF
Using sql server 2008's merge statement tech republic
Kaing Menglieng
 
PDF
Using object dependencies in sql server 2008 tech republic
Kaing Menglieng
 
PDF
Using hash fields in sql server tech republic
Kaing Menglieng
 
PDF
Using grouping sets in sql server 2008 tech republic
Kaing Menglieng
 
PDF
Understand when to use user defined functions in sql server tech-republic
Kaing Menglieng
 
PDF
Sql server indexed views speed up your select queries part 1 - code-projec
Kaing Menglieng
 
PDF
Sql server – query optimization – remove bookmark lookup – remove rid lookup
Kaing Menglieng
 
PDF
Sql server common interview questions and answers
Kaing Menglieng
 
PDF
Sql server common interview questions and answers page 6
Kaing Menglieng
 
PDF
Sql server common interview questions and answers page 5
Kaing Menglieng
 
PDF
Sql server common interview questions and answers page 4
Kaing Menglieng
 
PDF
Sql server common interview questions and answers page 2
Kaing Menglieng
 
PDF
Sql server – 2008 – hardware and software requirements for installing sql se
Kaing Menglieng
 
PDF
Speeding up queries with semi joins and anti-joins
Kaing Menglieng
 
PDF
Speed up sql
Kaing Menglieng
 
PDF
Speed up sql server apps - visual studio magazine
Kaing Menglieng
 
PDF
See sql server graphical execution plans in action tech republic
Kaing Menglieng
 
PDF
Query optimization how to search millions of record in sql table faster -
Kaing Menglieng
 
PDF
Optimize sql server queries with these advanced tuning techniques tech repu
Kaing Menglieng
 
What is your sql server backup strategy tech_republic
Kaing Menglieng
 
Using sql server 2008's merge statement tech republic
Kaing Menglieng
 
Using object dependencies in sql server 2008 tech republic
Kaing Menglieng
 
Using hash fields in sql server tech republic
Kaing Menglieng
 
Using grouping sets in sql server 2008 tech republic
Kaing Menglieng
 
Understand when to use user defined functions in sql server tech-republic
Kaing Menglieng
 
Sql server indexed views speed up your select queries part 1 - code-projec
Kaing Menglieng
 
Sql server – query optimization – remove bookmark lookup – remove rid lookup
Kaing Menglieng
 
Sql server common interview questions and answers
Kaing Menglieng
 
Sql server common interview questions and answers page 6
Kaing Menglieng
 
Sql server common interview questions and answers page 5
Kaing Menglieng
 
Sql server common interview questions and answers page 4
Kaing Menglieng
 
Sql server common interview questions and answers page 2
Kaing Menglieng
 
Sql server – 2008 – hardware and software requirements for installing sql se
Kaing Menglieng
 
Speeding up queries with semi joins and anti-joins
Kaing Menglieng
 
Speed up sql
Kaing Menglieng
 
Speed up sql server apps - visual studio magazine
Kaing Menglieng
 
See sql server graphical execution plans in action tech republic
Kaing Menglieng
 
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
Kaing Menglieng
 

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]