Wednesday, February 15, 2012

SqlServer SMO–Truncating logs

The TruncateLogs method (Database class) is not supported on SqlServer 2008 (and above).

Here is how you do it in SqlServer 2008 using PowerShell

$serverName = "server"
$databaseName = "database"

[System.Reflection.Assembly]::LoadWithPartialName('Microsoft.SqlServer.SMO') | out-null
$sqlServerSmo = New-Object -TypeName Microsoft.SqlServer.Management.Smo.Server ($serverName )
if ($sqlServerSmo.databases[$databaseName] -ne $null)
{
     $database = $sqlServerSmo.databases[$databaseName];
     if ($database)
    {
         $database.RecoveryModel = [Microsoft.SqlServer.Management.Smo.RecoveryModel]::Simple;
         $database.Alter();
         $database.LogFiles | ForEach-Object {
                $_.Shrink(2, [Microsoft.SqlServer.Management.Smo.ShrinkMethod]::Default);
         }

    }
}

And here is how you change the database owner (where $database is retrieved as shown in the snippet above).:

$database.SetOwner("SA");
$database.Alter();

No comments:

Post a Comment

Remember, if you want me to respond to your comment, then you need to use a Google/OpenID account to leave the comment.