Book Image

PowerShell for SQL Server Essentials

By : Donabel Santos
Book Image

PowerShell for SQL Server Essentials

By: Donabel Santos

Overview of this book

Table of Contents (15 chapters)
PowerShell for SQL Server Essentials
Credits
About the Author
Acknowledgments
About the Reviewers
www.PacktPub.com
Preface
Implementing Reusability with Functions and Modules
Index

Adding files and filegroups


Filegroups in SQL Server allow for a group of files to be managed together. It is almost akin to having folders on your desktop to allow you to manage, move, and save files together.

To add a filegroup, you have to use the Microsoft.SqlServer.Management.Smo.Filegroup class. Assuming you already have variables that point to your server instance, you can create a variable that references the database you wish to work with, as shown in the following snippet:

$dbname = "Registration"
$db = $server.Databases[$dbname]

Instantiating a Filegroup variable requires the handle to the SMO database object and a filegroup name. We have shown this in the following screenshot:

#code below is a single line
$fg = New-Object "Microsoft.SqlServer.Management.Smo.Filegroup" $db, "FG1"

When you're ready to create, invoke the Create() method:

$fg.Create()

Adding a datafile uses a similar approach. You need to identify which filegroup this new datafile belongs to. You will also need to...