Functions/Invoke-ShrinkDatabaseLogFile.ps1
<#
.SYNOPSIS Invoke a shrink of the log file of a given database name .DESCRIPTION Warning: This cmdlet sets the database recovery model to full. .EXAMPLE Invoke-ShrinkDatabaseLogFile -DatabaseName 'testxxx' .EXAMPLE Invoke-ShrinkDatabaseLogFile -DatabaseName 'testxxx' -SqlInstance 'fdb04' .EXAMPLE Invoke-ShrinkDatabaseLogFile -DatabaseName 'testxxx' -SqlInstance 'localhost/navdemo' .PARAMETER DatabaseName Name of the database .PARAMETER SqlInstance Name of the database server like "<hostname>[/<instance>]", default is local hostname. #> function Invoke-ShrinkDatabaseLogFile { [CmdletBinding()] param ( [parameter(Mandatory=$true)] [string] $DatabaseName, [parameter(Mandatory=$false)] [string] $SqlInstance = $env:COMPUTERNAME ) process { $DatabaseInfo = Invoke-Sqlcmd ("select * from master.dbo.sysdatabases where name='{0}'" -f $DatabaseName) -ServerInstance $SqlInstance if ([string]::IsNullOrEmpty($DatabaseInfo.dbid)) { throw ("Database {0} not found on server {1}" -f $DatabaseName, $SqlInstance) } $fileInfo = Invoke-Sqlcmd ('select name from sys.master_files where database_id = {0} and type = 1' -f $DatabaseInfo.dbid) -ServerInstance $SqlInstance Invoke-Sqlcmd -Query ("alter database {0} set recovery simple with no_wait" -f $DatabaseName) -ServerInstance $SqlInstance Invoke-Sqlcmd -Query ("DBCC SHRINKFILE('{0}')" -f $fileInfo.name) -Database $DatabaseName -ServerInstance $SqlInstance -Verbose:$false | Out-Null Invoke-Sqlcmd -Query ("alter database {0} set recovery full with no_wait" -f $DatabaseName) -ServerInstance $SqlInstance Write-Verbose ("Shrunk log file of database {0}" -f $DatabaseName) } } Export-ModuleMember Invoke-ShrinkDatabaseLogFile |