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

Creating a filegroup


This recipe describes how to create a filegroup programmatically using PowerShell and SMO.

Getting ready

We will add a filegroup called FGActive to your TestDB database. In this recipe, this is the T-SQL equivalent of what we are trying to accomplish:

ALTER DATABASE [TestDB]
ADD FILEGROUP [FGActive]
GO

How to do it...

These are the steps to add a filegroup to your database:

  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

    Add the following script and run:

    $databasename = "TestDB"
    $database = $server.Databases[$databasename]
    $fgname = "FGActive"
    
    #For purposes of this recipe, we are going to drop this
    #filegroup if it exists, so we can recreate it without
    #any issues
    if ($database.FileGroups[$fgname...