• Stars
    star
    2,441
  • Rank 18,844 (Top 0.4 %)
  • Language
    PowerShell
  • License
    MIT License
  • Created almost 10 years ago
  • Updated about 2 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

πŸš€ SQL Server automation and instance migrations have never been safer, faster or freer

Open in Visual Studio Code

Getting Started

dbatools logo dbatools is PowerShell module that you may think of like a command-line SQL Server Management Studio. The project initially started out as just Start-SqlMigration.ps1, but as of our 2.0 version release has grown into a collection of nearly 700 commands that help automate SQL Server tasks and encourage best practices.

Want to contribute to the project? We'd love to have you! Visit our contributing.md for a jump start.

Want to say thanks? Click the star at the top of the page 🌟

Key links for reference:

Need an invite to the SQL Community Slack workspace? Check out the self-invite page. Drop by if you'd like to chat about dbatools or even join the team!

Installer

dbatools works on Windows, Linux and macOS (M1 and Intel!) πŸ€©πŸ‘ Windows requires PowerShell v3 and above, while those using dbatools on PowerShell Core will need to be running 7.3 and above.

Run the following command to install dbatools from the PowerShell Gallery (to install on a server or for all users, remove the -Scope parameter and run in an elevated session):

Install-Module dbatools -Scope CurrentUser

If you use an earlier version of PowerShell that does not support the PowerShell Gallery, you can download PowerShellGet from Microsoft's site then run the command again.

Usage scenarios

In addition to the simple things you can do in SSMS (e.g. starting a job, backing up a database), we've also read a whole bunch of docs and came up with commands that do nifty things quickly.

  • Lost sysadmin access and need to regain entry to your SQL Server? Use Reset-DbaAdmin.
  • Need to easily test your backups? Use Test-DbaLastBackup.
  • SPN management got you down? Use our suite of SPN commands to find which SPNs are missing and easily add them.
  • Got so many databases you can't keep track? Congrats on your big ol' environment! Use Find-DbaDatabase to easily find your database.

Usage examples

As previously mentioned, dbatools now offers over 700 commands! Here are some of the ones we highlight at conferences.

PowerShell v3 and above required. (See below for important information about alternative logins and specifying SQL Server ports).

# Set some vars
$new = "localhost\sql2016"
$old = $instance = "localhost"
$allservers = $old, $new

# Alternatively, use Registered Servers
$allservers = Get-DbaRegServer -SqlInstance $instance

# Need to restore a database? It can be as simple as this:
Restore-DbaDatabase -SqlInstance $instance -Path "C:\temp\AdventureWorks2012-Full Database Backup.bak"

# Use Ola Hallengren's backup script? We can restore an *ENTIRE INSTANCE* with just one line
Get-ChildItem -Directory \\workstation\backups\sql2012 | Restore-DbaDatabase -SqlInstance $new

# What about if you need to make a backup? And you are logging in with alternative credentials?
Get-DbaDatabase -SqlInstance $new -SqlCredential sqladmin | Backup-DbaDatabase

# Testing your backups is crazy easy!
Start-Process https://dbatools.io/Test-DbaLastBackup
Test-DbaLastBackup -SqlInstance $old | Out-GridView

# But what if you want to test your backups on a different server?
Test-DbaLastBackup -SqlInstance $old -Destination $new | Out-GridView

# Nowadays, we don't just backup databases. Now, we're backing up logins
Export-DbaLogin -SqlInstance $instance -Path C:\temp\logins.sql
Invoke-Item C:\temp\logins.sql

# And Agent Jobs
Get-DbaAgentJob -SqlInstance $old | Export-DbaScript -Path C:\temp\jobs.sql

# What if you just want to script out your restore?
Get-ChildItem -Directory \\workstation\backups\subset\ | Restore-DbaDatabase -SqlInstance $new -OutputScriptOnly -WithReplace | Out-File -Filepath c:\temp\restore.sql
Invoke-Item c:\temp\restore.sql

# You've probably heard about how easy migrations can be with dbatools. Here's an example
$startDbaMigrationSplat = @{
    Source = $old
    Destination = $new
    BackupRestore = $true
    SharedPath = 'C:\temp'
    Exclude = 'BackupDevice','SysDbUserObjects','Credentials'
}

Start-DbaMigration @startDbaMigrationSplat -Force | Select-Object * | Out-GridView

# Know how snapshots used to be a PITA? Now they're super easy
New-DbaDbSnapshot -SqlInstance $new -Database db1 -Name db1_snapshot
Get-DbaDbSnapshot -SqlInstance $new
Get-DbaProcess -SqlInstance $new -Database db1 | Stop-DbaProcess
Restore-DbaFromDatabaseSnapshot -SqlInstance $new -Database db1 -Snapshot db1_snapshot
Remove-DbaDbSnapshot -SqlInstance $new -Snapshot db1_snapshot # or -Database db1

# Have you tested your last good DBCC CHECKDB? We've got a command for that
$old | Get-DbaLastGoodCheckDb | Out-GridView

# Here's how you can find your integrity jobs and easily start them. Then, you can watch them run, and finally check your newest DBCC CHECKDB results
$old | Get-DbaAgentJob | Where-Object Name -match integrity | Start-DbaAgentJob
$old | Get-DbaRunningJob
$old | Get-DbaLastGoodCheckDb | Out-GridView

# Our new build website is super useful!
Start-Process https://dbatools.io/builds

# You can use the same JSON the website uses to check the status of your own environment
$allservers | Get-DbaBuild

# We evaluated 37,545 SQL Server stored procedures on 9 servers in 8.67 seconds!
$new | Find-DbaStoredProcedure -Pattern dbatools

# Have an employee who is leaving? Find all of their objects.
$allservers | Find-DbaUserObject -Pattern ad\jdoe | Out-GridView

# Find detached databases, by example
Detach-DbaDatabase -SqlInstance $instance -Database AdventureWorks2012
Find-DbaOrphanedFile -SqlInstance $instance | Out-GridView

# Check out how complete our sp_configure command is
Get-DbaSpConfigure -SqlInstance $new | Out-GridView

# Easily update configuration values
Set-DbaSpConfigure -SqlInstance $new -ConfigName XPCmdShellEnabled -Value $true

# DB Cloning too!
Invoke-DbaDbClone -SqlInstance $new -Database db1 -CloneDatabase db1_clone | Out-GridView

# Read and watch XEvents
Get-DbaXESession -SqlInstance $new -Session system_health | Read-DbaXEFile
Get-DbaXESession -SqlInstance $new -Session system_health | Read-DbaXEFile | Select-Object -ExpandProperty Fields | Out-GridView

# Reset-DbaAdmin
Reset-DbaAdmin -SqlInstance $instance -Login sqladmin -Verbose
Get-DbaDatabase -SqlInstance $instance -SqlCredential sqladmin

# sp_whoisactive
Install-DbaWhoIsActive -SqlInstance $instance -Database master
Invoke-DbaWhoIsActive -SqlInstance $instance -ShowOwnSpid -ShowSystemSpids

# Diagnostic query!
$instance | Invoke-DbaDiagnosticQuery -UseSelectionHelper | Export-DbaDiagnosticQuery -Path $home
Invoke-Item $home

# Ola, yall
$instance | Install-DbaMaintenanceSolution -ReplaceExisting -BackupLocation C:\temp -InstallJobs

# Startup parameters
Get-DbaStartupParameter -SqlInstance $instance
Set-DbaStartupParameter -SqlInstance $instance -SingleUser -WhatIf

# Database clone
Invoke-DbaDbClone -SqlInstance $new -Database dbwithsprocs -CloneDatabase dbwithsprocs_clone

# Schema change and Pester tests
Get-DbaSchemaChangeHistory -SqlInstance $new -Database tempdb

# Get Db Free Space AND write it to table
Get-DbaDbSpace -SqlInstance $instance | Out-GridView
Get-DbaDbSpace -SqlInstance $instance -IncludeSystemDB | ConvertTo-DbaDataTable | Write-DbaDataTable -SqlInstance $instance -Database tempdb -Table DiskSpaceExample -AutoCreateTable
Invoke-DbaQuery -SqlInstance $instance -Database tempdb -Query 'SELECT * FROM dbo.DiskSpaceExample' | Out-GridView

# History
Get-Command -Module dbatools *history*

# Identity usage
Test-DbaIdentityUsage -SqlInstance $instance | Out-GridView

# Test/Set SQL max memory
$allservers | Get-DbaMaxMemory
$allservers | Test-DbaMaxMemory | Format-Table
$allservers | Test-DbaMaxMemory | Where-Object { $_.SqlMaxMB -gt $_.TotalMB } | Set-DbaMaxMemory -WhatIf
Set-DbaMaxMemory -SqlInstance $instance -MaxMb 1023

# Testing sql server linked server connections
Test-DbaLinkedServerConnection -SqlInstance $instance

# See protocols
Get-DbaServerProtocol -ComputerName $instance | Out-GridView

# Reads trace files - default trace by default
Read-DbaTraceFile -SqlInstance $instance | Out-GridView

# don't have remoting access? Explore the filesystem. Uses master.sys.xp_dirtree
Get-DbaFile -SqlInstance $instance

# Test your SPNs and see what'd happen if you'd set them
$servers | Test-DbaSpn | Out-GridView
$servers | Test-DbaSpn | Out-GridView -PassThru | Set-DbaSpn -WhatIf

# Get Virtual Log File information
Get-DbaDbVirtualLogFile -SqlInstance $new -Database db1
Get-DbaDbVirtualLogFile -SqlInstance $new -Database db1 | Measure-Object

Important Note

Alternative SQL Credentials

By default, all SQL-based commands will login to SQL Server using Trusted/Windows Authentication. To use alternative credentials, including SQL Logins or alternative Windows credentials, use the -SqlCredential. This parameter accepts the results of Get-Credential which generates a PSCredential object.

Get-DbaDatabase -SqlInstance sql2017 -SqlCredential sqladmin

A few (or maybe just one - Restore-DbaDatabase), you can also use -AzureCredential.

Alternative Windows Credentials

For commands that access Windows such as Get-DbaDiskSpace, you will pass the -Credential parameter.

$cred = Get-Credential ad\winadmin
Get-DbaDiskSpace -ComputerName sql2017 -Credential $cred

To store credentials to disk, please read more at Jaap Brasser's blog.

Servers with custom ports

If you use non-default ports and SQL Browser is disabled, you can access servers using a colon (functionality we've added) or a comma (the way Microsoft does it).

-SqlInstance sql2017:55559
-SqlInstance 'sql2017,55559'

Note that PowerShell sees commas as arrays, so you must surround the host name with quotes.

Using Start-Transcript

Due to an issue in the way PowerShell 5.1 works you need to use Import-Module dbatools before you run Start-Transcript. If this isn't done then your transcript will stop when the module is imported:

Import-Module dbatools
Start-Transcript
Get-DbaDatabase -SqlInstance sql2017
Stop-Transcript

Support

dbatools aims to support as many configurations as possible, including

  • PowerShell v3 and above
  • Windows, macOS and Linux
  • SQL Server 2000 - Current
  • Express - Datacenter Edition
  • Clustered and stand-alone instances
  • Windows and SQL authentication
  • Default and named instances
  • Multiple instances on one server
  • Auto-populated parameters for command-line completion (think -Database and -Login)

Read more at our website at dbatools.io

More Repositories

1

dbachecks

βœ” SQL Server Environmental Validation
PowerShell
461
star
2

dbops

βš™ dbops - Powershell module that provides continuous database deployments on any scale
PowerShell
155
star
3

DataSaturdays

A repository for open sourcing a solution for Data Saturdays
HTML
142
star
4

dbaclone

πŸ‘― Clone SQL Server databases using PowerShell previously named PSDatabaseClone
PowerShell
133
star
5

dbareports

PowerShell Module to gather, store and report on data about your estate. **This repository has been archived due to no longer being maintained.**
PowerShell
110
star
6

Invoke-SqlCmd2

PowerShell module containing Invoke-SqlCmd2
PowerShell
68
star
7

community-presentations

Presentation Repository for SQL Server / PowerShell Presentations within the Community
Jupyter Notebook
41
star
8

dbatools-templates

Templates for dbatools commands
PowerShell
30
star
9

dbatools-lab

Build a lab environment for testing out dbatools
Jupyter Notebook
22
star
10

mastodon

Where to find Data Platform, PowerShell and Power BI Twitter friends on Mastodon
20
star
11

docker

The code that's used to create the dbatools SQL Server images on Docker Hub.
TSQL
18
star
12

dbadisa

πŸ¦… DISA STIG automation module for SQL Server
PowerShell
16
star
13

docs

The documentation for dbatools module. Issues with command doc and bugs should be reported to dataplat/dbatools.
HTML
15
star
14

ADSNotebook

PowerShell Module for interacting with Azure Data Studio Notebooks
PowerShell
14
star
15

AlwaysEncryptedSample

Sample ASP.NET MVC Application for demonstrating Microsoft SQL Server Always Encrypted Functionality
C#
14
star
16

dbarefresh

πŸ”„ Database refresh module to copy partial data from production to another database
PowerShell
12
star
17

dataplat.github.io

Resources for the SQL Collaborative
HTML
11
star
18

AzureDataPipelineTools

A collection of Azure Function to make building Azure Data Factory pipeline simpler and easier.
C#
10
star
19

dbasecurityscan

Baseline, check and correct your SQL Database Security
PowerShell
10
star
20

dbatools.library

dbatools smo library builder
C#
7
star
21

dbatools-traininglab

a nice lil tutorial to help with useful tutorials
4
star
22

ssis-reporting-pack

3
star
23

dbatools-lab-dotnet-extension

This repo will hold the code to make the Azure Data Studio Extension for the dbatools dotnet interactive Notebooks which enables you to run dbatools against a couple of containers on your machine
Jupyter Notebook
3
star
24

disa-docs

Crowd-sourced Template for SQL Server Documentation as required by DISA
3
star
25

DataSpeakers

A simple repository which can serve as a resource for event owners to find speakers. The data is displayed on https://callfordataspeakers.com/precon and controlled with GitHub Issues and GitHub Actions
Shell
3
star
26

appveyor-lab

repo for full-on appveyor tests
TSQL
2
star
27

AlwaysEncryptedSample.Docs

2
star
28

sqlpsweb

basically a redirector
HTML
2
star
29

dbatools-libary

Source code to the dbatools.dll library utilized by dbatools PowerShell module
C#
2
star
30

dbachecksweb

redirector site for dbachecks.io
HTML
1
star
31

yourrole

Shell
1
star
32

web

dbatools.io website
HTML
1
star