THE SQL Server Blog Spot on the Web

Welcome to - The SQL Server blog spot on the web Sign in | |
in Search

Ben Miller

Powershell, SMO and Database Files

In response to some questions about renaming a physical file for a database, I have 2 versions of Powershell scripts that do this for you, including taking the database offline and then online to make the physical change match the meta-data.

First, there is an article about this at  This explains that you start by setting the database offline, then alter the database and modify the filename then set it back online.  This particular article does not show the physical renaming of the file, but it is necessary since the ALTER DATABASE MODIFY FILE statement only changes the metadata of the database in master.

There is a procedure to do this with SQL CLR and TSQL, but I chose to illustrate it in Powershell and SMO (using SQL Provider as well as straight SMO).  The SQLCLR version is by a SQL Server MVP, Ted Krueger (Blog | Twitter) and can be found at this link.

My version will be based on Powershell and SMO with a smattering of SQL Provider provided in SQL 2008+.

Code Snippet
  1. Add-PSSnapin SqlServerCmdletSnapin100
  2. Add-PSSnapin SqlServerProviderSnapin100
  3. $servername = "localhost"
  4. $instance = "default"
  5. $dbname = "N2CMS"
  6. $logicalName = "N2CMS"
  7. $NewPath = "c:\program files\microsoft sql server\mssql10_50.mssqlserver\mssql\data"
  8. $NewFilename = "N2CMS_4.mdf"
  9. if(Test-Path "sqlserver:\sql\$servername\$instance\databases\$dbname")
  10. {
  11.         $database = Get-Item("sqlserver:\sql\$servername\$instance\databases\$dbname");
  12.         $fileToRename = $database.FileGroups["PRIMARY"].Files[$logicalName]
  13.         $InitialFilePath = $fileToRename.FileName
  14.         $fileToRename.FileName = "$NewPath\$NewFilename"
  15.         $database.Alter();
  16.         $database.SetOffline()
  17.         Rename-Item -Path $InitialFilePath -NewName "$NewFilename"
  18.         $database.SetOnline()
  19.         Write-Host "File Renamed"
  20. }
  21. else
  22. {
  23.         Write-Host "Database does not exist";
  24. }

If you notice, I first add the Snapin that is the SQL Provider.  If you already have it loaded in your Powershell Profile, then you can just omit those lines.  If you do not have SQL 2008 objects installed on this machine, then you will notice that the Snapins don’t load either.  In that case you would just use the version below.

In the SQL Provider version you will see a Powershellism with Test-Path and you are using a path, it just is a SQL provider path that points to the Database and makes sure that it exists.  Compare it to the other version where you are looking at the Server.Databases[$dbname] and then you get the filegroups and then the files.

This version of the script is purely SMO and PowerShell.  First you load the objects from SQL Server 2005/2008 SMO.

Code Snippet
  1. # Always
  2. [System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SqlServer.SMO") | out-null
  3. # Only if you don't have SQL 2008 SMO Objects installed
  4. [System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SqlServer.SmoEnum") | out-null
  5. # Only if you have SQL 2008 SMO objects installed
  6. [System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SqlServer.SqlEnum") | out-null
  7. $servername = "localhost"
  8. $instance = "default"
  9. $dbname = "N2CMS"
  10. $logicalName = "N2CMS"
  11. $NewPath = "c:\program files\microsoft sql server\mssql10_50.mssqlserver\mssql\data"
  12. $NewFilename = "N2CMS_4.mdf"
  13. $server = New-Object -TypeName Microsoft.SqlServer.Management.Smo.Server -ArgumentList $servername
  14. if($server.Databases[$dbname] != $null)
  15. {
  16.         $database = $server.Databases[$dbname];
  17.         $fileToRename = $database.FileGroups["PRIMARY"].Files[$logicalName]
  18.         $InitialFilePath = $fileToRename.FileName
  19.         $fileToRename.FileName = "$NewPath\$NewFilename"
  20.         $database.Alter();
  21.         $database.SetOffline()
  22.         Rename-Item -Path $InitialFilePath -NewName "$NewFilename"
  23.         $database.SetOnline()
  24.         Write-Host "File Renamed"
  25. }
  26. else
  27. {
  28.         Write-Host "Database does not exist";
  29. }

This version will use the Server object to get the database that you are looking for so that you can get at the files.  The file you are looking for is the $logicalName so that you can get the PhysicalName of the file.  Then using the builtin CmdLets to handle Files operations, a Rename-Item is issued to rename the initial path to the new one.

Operation order:

  • Rename-Item from old to new

I did not put these in a function, but they could easily (or not too hard that is) put together using Parameters and make it versatile for other situations, but that is for you to do so that it works for your scenario.

Love PowerShell!

Published Monday, February 14, 2011 2:08 PM by dbaduck
Filed under: , ,


No Comments
New Comments to this post are disabled

About dbaduck

Ben Miller is a Senior Database Administrator for HealthEquity in Draper, UT. He has been working with SQL since SQL Server 6.0 (1998) and has had a variety of roles in his career, including SQL Support and MVP Lead at Microsoft.
Privacy Statement