Book Image

SQL Server 2014 with PowerShell v5 Cookbook

By : Donabel Santos
Book Image

SQL Server 2014 with PowerShell v5 Cookbook

By: Donabel Santos

Overview of this book

Table of Contents (21 chapters)
SQL Server 2014 with PowerShell v5 Cookbook
Credits
About the Author
Acknowledgments
About the Reviewers
www.PacktPub.com
Preface
Index

Running DBCC commands


This recipe shows you some of the DBCC commands that can be run using PowerShell.

How to do it...

Follow these steps to run DBCC commands:

  1. Open PowerShell ISE as administrator.

  2. Import the SQLPS module and create a new SMO Server object:

    #import SQL Server module
    Import-Module SQLPS -DisableNameChecking
    
    #replace this with your instance name
    $instanceName = "localhost"
    $server = New-Object -TypeName Microsoft.SqlServer.Management.Smo.Server -ArgumentList $instanceName
  3. Some DBCC commands are built into SMO, so you can just call the methods:

    $databasename = "AdventureWorks2014"
    $database = $server.Databases[$databasename]
    #RepairType Values: AllowDataLost, Fast, None, Rebuild
    $database.CheckTables([Microsoft.SqlServer.Management.Smo.RepairType]::None)

How it works...

Not all DBCC commands are wrapped in SMO methods. Some of the available methods are on a database level are as follows:

  • CheckAllocations

  • CheckAllocationsDataOnly

  • CheckCatalog

  • CheckTables

  • CheckTablesDataOnly

To...