Skip to content

Instantly share code, notes, and snippets.

@abombss
Created March 6, 2013 21:22
Show Gist options
  • Save abombss/5103204 to your computer and use it in GitHub Desktop.
Save abombss/5103204 to your computer and use it in GitHub Desktop.
Powershell LocalDb Wrapper
function Start-LocalDb {
[CmdletBinding()]
param(
[Parameter(Mandatory,ValueFromPipeLine,Position=1)]
[psobject[]]$Instance,
[string]$ToolPath = (Find-LocalDbExe)
)
begin {
}
process {
foreach($db in $Instance) {
if ($db -isnot [string]) {
$db = $db.InstanceName
}
if (Test-LocalDb $db -IsRunning) {
Write-Verbose "$db is already running"
} else {
(Invoke-LocalDb start,$db -ToolPath $ToolPath) | Write-Verbose
}
Get-LocalDb $db -ToolPath $ToolPath
}
}
end {
}
}
function Stop-LocalDb {
[CmdletBinding()]
param(
[Parameter(Mandatory,ValueFromPipeLine,Position=1)]
[psobject[]]$Instance,
[switch]$NoWait,
[switch]$Kill,
[string]$ToolPath = (Find-LocalDbExe)
)
begin {
}
process {
foreach($db in $Instance) {
if ($db -isnot [string]) {
$db = $db.InstanceName
}
if (Test-LocalDb $db -IsNotRunning) {
Write-Verbose "$db is not running"
} else {
$cmdArgs = @('stop',$db)
if ($Kill) { $cmdArgs += @('-k') }
elseif ($NoWait) { $cmdArgs += @('-i') }
(Invoke-LocalDb $cmdArgs -ToolPath $ToolPath) | Write-Verbose
}
Get-LocalDb $db -ToolPath $ToolPath
}
}
end {
}
}
function Enable-LocalDbSharing {
[CmdletBinding()]
param(
[Parameter(Mandatory,Position=1)]
[psobject]$Instance,
[string]$ShareName = $Instance,
[string]$ToolPath = (Find-LocalDbExe)
)
foreach($db in $Instance) {
if ($db -isnot [string]) {
$db = $db.InstanceName
}
if (Test-LocalDb $db -IsShared) {
Write-Verbose "$db is already shared"
} else {
(Invoke-LocalDb share,$db,$ShareName -ToolPath $ToolPath) | Write-Verbose
}
Get-LocalDb ".\$ShareName" -ToolPath $ToolPath
}
}
function Disable-LocalDbSharing {
[CmdletBinding()]
param(
[Parameter(Mandatory,Position=1)]
[psobject]$Instance,
[string]$ToolPath = (Find-LocalDbExe)
)
foreach($db in $Instance) {
if ($db -isnot [string]) {
$db = $db.InstanceName
}
if (Test-LocalDb $db -IsNotShared) {
Write-Verbose "$db is not shared"
} else {
(Invoke-LocalDb unshare,$db -ToolPath $ToolPath) | Write-Verbose
}
Get-LocalDb $db -ToolPath $ToolPath
}
}
function Enable-LocalDbTracing {
[CmdletBinding()]
param(
[string]$ToolPath = (Find-LocalDbExe)
)
(Invoke-LocalDb trace,on) | Write-Verbose
}
function Disable-LocalDbTracing {
[CmdletBinding()]
param(
[string]$ToolPath = (Find-LocalDbExe)
)
(Invoke-LocalDb trace,off) | Write-Verbose
}
function Add-LocalDb {
param(
[Parameter(Mandatory, Position=1)]
[string]$Instance,
[string]$Version,
[string]$SharedName,
[switch]$Start,
[switch]$Share,
[string]$ToolPath = (Find-LocalDbExe)
)
$cmdArgs = @('create',$Instance)
if ($Version) { $cmdArgs += @($Version) }
if ($Start) { $cmdArgs += @("-s") }
Invoke-LocalDb $cmdArgs -ToolPath $ToolPath | Write-Verbose
if ($Share) {
if (!$SharedName) { $SharedName = $Instance }
Enable-LocalDbSharing $Instance $SharedName | Out-Null
}
Get-LocalDb $Instance
}
function Remove-LocalDb {
param(
[Parameter(Mandatory, Position=1)]
[string]$Instance
)
Invoke-LocalDb delete,$Instance | Write-Verbose
}
function Test-LocalDb {
[CmdletBinding()]
param(
[Parameter(Mandatory)]
[string]$InstanceName,
[switch]$IsRunning,
[switch]$IsNotRunning,
[switch]$IsShared,
[switch]$IsNotShared
)
[scriptblock[]]$tests = @()
if ($IsRunning) { $tests += @({param($info) $info.State -eq 'Running'}) }
if ($IsNotRunning) { $tests += @({param($info) $info.State -ne 'Running'}) }
if ($IsShared) { $tests += @({param($info) $info.SharedName -ne [String]::Empty }) }
if ($IsNotShared) { $tests += @({param($info) $info.SharedName -eq [String]::Empty }) }
$localdb = Get-LocalDb $InstanceName -ErrorAction SilentlyContinue | select-object -first 1
$result = $true;
if (-not $localdb) {
$result = $false
} else {
foreach($test in $tests) {
if (!(&$test $localdb)) {
$result = $false
break;
}
}
}
$result
}
function Get-LocalDb {
param(
[Parameter(Position=1,ValueFromPipeline=$true)]
[string[]]$InstanceName,
[string]$ToolPath = (Find-LocalDbExe)
)
process {
if ((-not $InstanceName) -or ($InstanceName.Count -eq 0)) {
# Get a list of all instances
$InstanceName = Invoke-LocalDb info -ToolPath $ToolPath
}
foreach($instance in $InstanceName) {
[string[]] $result = Invoke-LocalDb info,$instance -ToolPath $ToolPath
Write-Verbose ([string]::Join("`n", $result))
[hashtable]$props = @{ }
foreach($line in $result) {
# Fix error handling, why is sqllocaldb.exe returning 0 on errors here, it should exit with non zero exit code?
if ($line -and $line.Contains("error:")) {
throw ([String]::Join("`n", $result))
}
# TODO: Fix this parsing and switch its aweful
[string[]]$parts = $line.Split(':', 2)
if ( ($parts.Count -ge 1) -and ($parts[1])) {
$value = $parts[1].Trim()
} else {
$value = [String]::Empty
}
$props.InstanceName = $instance
switch ($parts[0]) {
'State' { $props.State = $value }
'Auto-create' { $props.AutoCreate = ($value -eq 'yes') }
'Version' { $props.Version = $value }
'Instance pipe name' { $props.PipeName = $value }
'Last start time' { $props.LastStartTime = [DateTime]::Parse($value) }
'Owner' { $props.Owner = $value }
'Name' { $props.Name = $value }
'Shared name' { $props.SharedName = $value }
}
}
new-object psobject -Property $props
}
}
}
function Find-LocalDbExe {
if (get-command fSqlLocalDb.exe -ErrorAction SilentlyContinue) {
(Get-Command SqlLocalDb.exe).Path
} else {
# Search the registry for the sql install and local db
$sqlinstall = get-childitem 'HKLM:\SOFTWARE\Microsoft\Microsoft SQL Server\' |
? { ((split-path $_.name -Leaf) -match '^\d+$') -and (test-path (join-path $_.pspath 'tools\ClientSetup')) } |
select-object -last 1
#Write-Host $sqlinstall
$pathToSqlTools = (Get-Item (join-path $sqlinstall.pspath '\tools\ClientSetup')).GetValue("Path")
#Write-Host $pathToSqlTools
$localDb = join-path $pathToSqlTools 'SqlLocalDb.exe'
if (Test-Path $localDb) {
$localDb
} else {
Write-Error "Could not find a sql localdb installed"
}
}
}
function Invoke-LocalDb {
[CmdletBinding()]
param(
[Parameter(Position=1)]
[string[]] $CommandArgs,
[string]$ToolPath = (Find-LocalDbExe)
)
if (!(Test-Path $ToolPath)) {
throw (new-object System.IO.FileNotFound($ToolPath))
}
Exec { & $ToolPath $CommandArgs }
}
function Exec
{
[CmdletBinding()]
param (
[Parameter(Position=0, Mandatory=1)]
[scriptblock]$Command,
[Parameter(Position=1, Mandatory=0)]
[string]$ErrorMessage = "Execution of command failed.`n$Command"
)
& $Command
if ($LastExitCode -ne 0) {
throw "Exec: $ErrorMessage"
}
}
Export-ModuleMember -function Get-LocalDb,
Test-LocalDb,
Find-LocalDbExe,
Add-LocalDb,
Remove-LocalDb,
Start-LocalDb,
Stop-LocalDb,
Enable-LocalDbSharing,
Disable-LocalDbSharing,
Enable-LocalDbTracing,
Disable-LocalDbTracing
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment