LocalDb and SMO - how to choose where to put database files?

梦想与她 提交于 2019-12-25 05:59:14

问题


I've started to experiment with the SQL Server 2012 feature LocalDb. I'm doing some powershell scripting with SMO against the instances I create, such as creating databases. To do this, I have this function:

Function New-Database {
    Param(
        $server,
        $databaseName
    )
    $serverHandle = New-Object Microsoft.SqlServer.Management.Smo.Server($server)
    if($serverHandle.Databases.Name.Contains($databaseName)) {
        throw "Database $databaseName already exists"
    }

    $databaseHandle = New-Object Microsoft.SqlServer.Management.Smo.Database($serverHandle, $databaseName)
    $databaseHandle.Create()
}

When using LocalDb, the mdf and ldf files are created in C:\Users\<username>\. I want to override this, but I'm failing to find out how. The $databaseHandle object has a property PrimaryFilePath, but that is read-only. It seems like something that should be dead-simple to do, but I just can't find out how...

Solution Led by the answer below, here is the Powershell calls I needed:

    $fileGroup = New-Object Microsoft.SqlServer.Management.Smo.FileGroup($databaseHandle, "PRIMARY")
    $dataFile = New-Object Microsoft.SqlServer.Management.Smo.DataFile($fileGroup, "DataFile", $filePath)
    $fileGroup.Files.Add($dataFile)
    $databaseHandle.FileGroups.Add($fileGroup)

回答1:


I think this thread from the SMO Forum contains the answer. You just need to translate it to SQL PowerShell syntax (which I believe is just a wrapper to SMO at this point).

Here's the VBScript snippet:

databaseHandle.FileGroups.Add(New FileGroup(db, "PRIMARY"))
databaseHandle.FileGroups(0).Files.Add(
    New DataFile(db.FileGroups(0), "TestName", "D:\SqlBancos\Teste\Teste1.mdf"))


来源:https://stackoverflow.com/questions/14998233/localdb-and-smo-how-to-choose-where-to-put-database-files

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!