
Tag : datafiler,krympa,script,SQL Server
Ibland händer det att man får filer som har för mycket ledigt utrymme, för att då krympa den kan man köra det här scriptet.
Det går att sätta i hur stora steg man ska krympa den i. Ibland går det inte köra i ett enda stort steg.
Om detta inte funkar så kör en backup innan utifall det finns data som inte går att "flytta" på. Om det är riktigt tjurigt kan det vara som så att databasen till och med behöver sättas i simple mode, men det gäller oftast logfiler.
För tillfället är det endast för databaser med en fil, men utveckling pågår
Först krympning för datafiler
[System.Reflection.Assembly]::LoadWithPartialName('Microsoft.SqlServer.SMO') | out-null
# Sets environment parameters
$ConnectionString = "Server_name"
$DbName = "DB_Name"
$Server = New-Object ('Microsoft.SqlServer.Management.Smo.Server') $ConnectionString
$Db = $Server.Databases | Where-Object { $_.Name -eq $DbName }
# This number sets the available space after the operation is done. the value is in Mb
$Stopsize = "5000"
# Sets the size of how much you want to shrink each iteration. This is in Mb
$Stepsize = 100
# Checks filesizes
$Files = $Db.Filegroups.files
$File = $Files.Name
$StartingSize = [math]::Truncate(($Files.Size / 1024))
# Checks available space in the file
$SpaceAvailable = [math]::Truncate(($Files.Size - $Files.UsedSpace) / 1024)
# Sets the endsize.
$EndSize = [math]::Truncate(($StartingSize - $SpaceAvailable + $StopSize))
# The loop that does the operation
$NewSize = $StartingSize - $Stepsize
$I = $NewSize
while ($I -gt $EndSize)
{
$NewSize = $NewSize - $Stepsize
$DbccQuery = @"
DBCC SHRINKFILE($File, $NewSize)
"@
Invoke-Sqlcmd -ServerInstance $ConnectionString -Query $DbccQuery -Database $Db.Name
Write-Host $DbccQuery
$I = $I - $Stepsize
}
Och här för logfiler
[System.Reflection.Assembly]::LoadWithPartialName('Microsoft.SqlServer.SMO') | out-null
# Sets environment parameters
$ConnectionString = "Server_name"
$DbName = "DB_Name"
$Server = New-Object ('Microsoft.SqlServer.Management.Smo.Server') $ConnectionString
$Db = $Server.Databases | Where-Object { $_.Name -eq $DbName }
# This number sets the available space after the operation is done. the value is in Mb
$Stopsize = "5000"
# Sets the size of how much you want to shrink each iteration. This is in Mb
$Stepsize = 100
# Checks filesizes
$Files = $Db.logfiles
$File = $Files.Name
$StartingSize = [math]::Truncate(($Files.Size / 1024))
# Checks available space in the file
$SpaceAvailable = [math]::Truncate(($Files.Size - $Files.UsedSpace) / 1024)
# Sets the endsize.
$EndSize = [math]::Truncate(($StartingSize - $SpaceAvailable + $StopSize))
# The loop that does the operation
$NewSize = $StartingSize - $Stepsize
$I = $NewSize
while ($I -gt $EndSize)
{
$NewSize = $NewSize - $Stepsize
$DbccQuery = @"
DBCC SHRINKFILE($File, $NewSize)
"@
Invoke-Sqlcmd -ServerInstance $ConnectionString -Query $DbccQuery -Database $Db.Name
Write-Host $DbccQuery
$I = $I - $Stepsize
}