Giter Club home page Giter Club logo

dbatools's Introduction

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

dbatools's People

Contributors

alevyinroc avatar andreasjordan avatar awickham10 avatar claudioessilva avatar constantinek avatar cviorel avatar dansqldba avatar friedrichweinmann avatar gbargsley avatar josh-simar avatar joshcorr avatar jpomfret avatar lancasteradam avatar lowlydba avatar mikepetrak avatar mikeybronowski avatar niphlod avatar nvarscar avatar olegstrutinskii avatar potatoqualitee avatar powerdbaklaas avatar sanderstad avatar sircaptainmitch avatar splaxi avatar sqldbawithabeard avatar sqllensman avatar staggerlee011 avatar stuart-moore avatar wsmelton avatar zippy1981 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

dbatools's Issues

Not really an issue but suggestion

Can I suggest adding the option to backup to multiple files for larger databases? I have seen a 50 percent increase in performance on backups and restores.

Copy-SqlJob does not copy maintenance plans

If you are dealing with maintenance plans (not custom SSIS packages) for a given instance the cmdlet is only copying the job definition, not the actual maintenance plan.

Do we want cmdlet for copying maintenance plans or include T-SQL to copy msdb.dbo.sysssispackages (just maintenance plans) to destination. Other option would be to look at using SMO for SSIS to export the packages, but T-SQL likely going to be much less painful. Possibly this code: http://dba.stackexchange.com/a/112434/507

Export-SqlLogin - Errors in HELP Part and Website - ParameterName wrong

Hi,
today I've tried to export a single SQLServerLogin by using the example from the website (similiar to HELP Part)
Export-SqlLogin -SqlServer SQLServerName -Login testsqlserveruser -FileName C:\temp\login_export.sql

But that won't work on my Windows 2008R2 + SQLServer 2012 EE
A little Research showed me that the Parameter is FilePath instead of FileName and on my machine i got the error that it can't resolve the parameter binding with its position....

The only way it worked for me on my machine was
Export-SqlLogin -SqlServer Servername\InstanceName -Login testsqlserveruser --FileName C:\temp\login_export.sql

And it would be very nice if you could make it a little bit clearer what -SqlServer means... only the servername or only instance... ok with a little bit of thinking you can resolve it by yourself but a hint could make it a little bit easier.

Instead of:
.PARAMETER SqlServer
The SQL Server to export the logins from. SQL Server 2000 and above supported.

it would nicer (e.g.)
.PARAMETER SqlServer
Complete SQL Servername with InstanceName without quotes. SQL Server 2000 and above supported.

Copy-SqlLogin should not require sysadmin privileges

Our PS/Sysadmin commented out some of the root-level checks to remove the "sysadmin" requirement. However, this should probably be changed to something a bit more appropriate to check the actual permissions required (securityadmin?).

We were able to run the copy-sqllogin function with the source user set as a security admin.

Copy-SqlLinkedServer ignored Linked server

I ran Copy-SqlLinkedServer in both -WhatIf and not whatif mode and it ignored a linked server that was 2 characters long, "SQ".

Here is the script for creating the Linked Server for more information so you can try to diagnose what went wrong:

USE [master]
GO

/****** Object: LinkedServer [SQ] Script Date: 1/11/2016 3:23:27 PM *****/
EXEC master.dbo.sp_addlinkedserver @server = N'SQ', @srvproduct=N'Cache ODBC', @Provider=N'MSDASQL.1', @datasrc=N'LABSQ'
/
For security reasons the linked server remote logins password is changed with ######## */
EXEC master.dbo.sp_addlinkedsrvlogin @rmtsrvname=N'SQ',@useself=N'False',@locallogin=NULL,@rmtuser=NULL,@rmtpassword=NULL

GO

EXEC master.dbo.sp_serveroption @server=N'SQ', @optname=N'collation compatible', @optvalue=N'false'
GO

EXEC master.dbo.sp_serveroption @server=N'SQ', @optname=N'data access', @optvalue=N'true'
GO

EXEC master.dbo.sp_serveroption @server=N'SQ', @optname=N'dist', @optvalue=N'false'
GO

EXEC master.dbo.sp_serveroption @server=N'SQ', @optname=N'pub', @optvalue=N'false'
GO

EXEC master.dbo.sp_serveroption @server=N'SQ', @optname=N'rpc', @optvalue=N'false'
GO

EXEC master.dbo.sp_serveroption @server=N'SQ', @optname=N'rpc out', @optvalue=N'false'
GO

EXEC master.dbo.sp_serveroption @server=N'SQ', @optname=N'sub', @optvalue=N'false'
GO

EXEC master.dbo.sp_serveroption @server=N'SQ', @optname=N'connect timeout', @optvalue=N'0'
GO

EXEC master.dbo.sp_serveroption @server=N'SQ', @optname=N'collation name', @optvalue=null
GO

EXEC master.dbo.sp_serveroption @server=N'SQ', @optname=N'lazy schema validation', @optvalue=N'true'
GO

EXEC master.dbo.sp_serveroption @server=N'SQ', @optname=N'query timeout', @optvalue=N'0'
GO

EXEC master.dbo.sp_serveroption @server=N'SQ', @optname=N'use remote collation', @optvalue=N'true'
GO

EXEC master.dbo.sp_serveroption @server=N'SQ', @optname=N'remote proc transaction promotion', @optvalue=N'false'
GO

Local <> Local Server

The local <> local server check has bad logic. Expects to always migrate remotely.

Restore-HallengrenBackup error, not sure why

Hi.
First off, great work, thank you for this set of scripts. They look neat.

Now, I noticed that the detach/attach method does not attach again in the old server. And then I had permission troubles attaching again ( ?!?! )
So I was testing the restore from backup method, so I can maintain source server working with ease, if needed.

My backups are made using Ola's set of scripts. So I tested the restore-hallengrenBackup

My the error is:

File list could not be determined. This is likely due to connectivity issues or tiemouts with the SQL Server, the
database version is incorrect, or the SQL Server service account does not have access to the file share. Script
terminating.
At C:\Users\Administrator\Documents\WindowsPowerShell\Modules\dbatools\Functions\Restore-HallengrenBackups.ps1:206
char:12
+             catch { throw "File list could not be determined. This is likely due to conne ...
+    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : OperationStopped: (File list could...pt terminating.:String) [], RuntimeException
    + FullyQualifiedErrorId : File list could not be determined. This is likely due to connectivity issues or tiemouts
    with the SQL Server, the database version is incorrect, or the SQL Server service account does not have access to
   the file share. Script terminating.

Could it be that -Path doesn't work as a NetworkPath?
Maybe I need to copy the backups to this machine? If so, could you add -NetworkPath parameter?

BatchParser error in ExportImportSqlConfig.ps1

Migrating SQL Server Configuration
Start-SqlMigration : Configuration migration reported the following error Exception calling "ExecuteNonQuery" with "1" argument(s): "Could not load file or assembly 'Microsoft.SqlServer.BatchParser, Version=10.0.0.0, Culture=neutral,
PublicKeyToken=89845dcd8080cc91' or one of its dependencies. The system cannot find the file specified."

copy-sqldatabase, no exclude parameter

In the comments and help both show a exclude command to limit which DBs are copied. However when running the function the exclude command is not a valid parameter.

Test-SqlTempDbConfiguration - tempdb on C: validation

This is not working as expected.
Was running a test on a server with only C drive and the test was false. Should be true.
After debug I saw that we are using:
($datafiles.rows | Where-Object { $.FileName -like 'C:*' }).Rows.Count
but should be:
@($datafiles.rows | Where-Object { $
.FileName -like 'C:*' }).Count

@MikeFal want to make the correction? Or can I make it?

test-sqltempdbconfiguration_bug

Event notifications and related permissions disappear

Found that event notifications can get lost when you convert. Found that you have to re-apply connect permissions. Note, ensure broker got copied over, I have seen where it has not.

(Chrissy LeMaire)

@js0505 You are a gold mine! Thank you. Can you give me steps to reproduce? Some T-SQL from start to finish would be great.

(js0505)

During my next migration from a system that contains EN I will work on generating the script for you. We are doing migrations all month so hopefully next week.

(Chrissy LeMaire)

@js0505 when you say " ensure broker got copied over", is that the Broker Enabled or something else? I don't use Event Notifications, but they look like they are scoped at the DB. Is this accurate? Are they usually copied properly during backup/restore?

(js0505)

Broker Enabled, and yes "usually" everything gets copied over, however, there are times I have to GRANT CONNECT ON::ServiceBroker TO ACCOUNT on the endpoint server.

Get-DbaDiskSpace - Output format issue

Get-DbaDiskSpace - Output format might give an error like "Cannot convert value "1.010.880,00" to type "System.Int64"" when try to set the value to an int/long variable. It is not really a bug is an improvement that can be made to the digit symbol group not be returned.

For example: 1.010.880,00 should be returned to: 1010880,00

Here I'm trying to set the value for an [long]$variable the FreeInKB from the Get-DbaDiskSpace.

Obviously I can replace the '.' or ',' for '' and work, but I think once this command can and should be reused should be more generic.
Thoughts?

Issue with named instances

Hi,

I am having issues with running migrations on from/to named instances.

For example, if I run:

Copy-SqlLinkedServer -Source server\instance -Destination server\instance2

I get the following error:
WARNING: could not be added to server\instance
WARNING: Reason: System.Management.Automation.RuntimeException: The regular expression pattern 'server\instance' is not valid. ---> System.ArgumentException: parsing "'server\instance'" - Unrecognized escape sequence \i.
at System.Text.RegularExpressions.RegexParser.ScanCharEscape()
at System.Text.RegularExpressions.RegexParser.ScanBasicBackslash()
at System.Text.RegularExpressions.RegexParser.ScanRegex()
at System.Text.RegularExpressions.RegexParser.Parse(String re, RegexOptions op)
at System.Text.RegularExpressions.Regex..ctor(String pattern, RegexOptions options, TimeSpan matchTimeout, Boolean useCache)
at System.Text.RegularExpressions.Regex..ctor(String pattern, RegexOptions options)
at System.Management.Automation.ParserOps.NewRegex(String patternString, RegexOptions options)
at System.Management.Automation.ParserOps.ReplaceOperator(ExecutionContext context, IScriptExtent errorPosition, Object lval, Object rval, Boolean ignoreCase)
--- End of inner exception stack trace ---
at System.Management.Automation.ExceptionHandlingOps.CheckActionPreference(FunctionContext funcContext, Exception exception)
at lambda_method(Closure , Object[] , StrongBox`1[] , InterpretedFrame )

Copy-SqlLogin issues

  • Detect schema ownership prior to user drop attempt
  • Will not drop login in destination if permissions are set
  • Test task

Copy-SqlJob may be duplicating actions

During testing for PR #133 I noticed the -Whatif output seemed to be duplicating.

What if: Performing the operation "Creating Job Some Report Job" on target "somesqlserver".
What if: Performing the operation "Creating Job Some Report Job" on target "somesqlserver".
What if: Performing the operation "Showing finished message" on target "console".

Without the WhatIf (still including -Verbose, easier to see when you remove the Write-Verbose $sql line, otherwise verbose outputs all the SQL used):

VERBOSE: Performing the operation "Creating Job Some Report Job" on target "somesqlserver".
Copying Job Some Report Job
VERBOSE: Performing the operation "Creating Job Some Report Job" on target "somesqlserver".
Disabling Some Report Job on somesqlserver
VERBOSE: Performing the operation "Showing finished message" on target "console".
Job migration finished

Expand-SqlTlogResponsibly backups when -WhatIf is declared

If I run this command with the -WhatIf switch to validate what it's going to do, it backs up anyway. This could be problematic and generate uneeded backups, along with possibly disrupting the log backup chain. I suggest that this get altered that if -WhatIf is declared it will provide a message that a log backup will be taken, but not execute.

General - Do not strip FQDN

If someone specifies an FQDN, reattach the domain back to the server name when testing for netbios/ip/etc. $server.ComputerNamePhysicalNetBIOS + $domain. This impacts many commands, including Remove-SqlDatabaseSafely which broke for me because the server's dns wasn't in my search suffix.

Detect Fatal Backup/Restore messages, and error out.

Right now, backup/restore keeps trying and continues on through each specified database, even when some errors are encountered. That's acceptable in some instances, but in others, it is not.

An example of a non-recoverable error would be: Cannot open backup device xyz. Operating system error 52(You were not connected because a duplicate name exists on the network. Go to System in Control Panel to change the computer name and try again.).

Break down what perms are needed per command

Break down what perms are needed per command, then we can add support for those roles/needs in Connect-SqlServer.

Right now, I have -RegularUser which simply doesn't check for role membership, but that's all.

Remove-SqlDatabaseSafely - SQL Agent check

The check isn't accurate. Copy-SqlAgent stuff has a more accurate check. In this case, Agent was running but couldn't be verified, and the script attempted to start Agent. In SSMS, the circle was white. Probably related.

Copy-SqlJob does not -DisableOnDestination

I ran Copy-SqlJob on an array of jobnames with -DisableOnDestination. When I reviewed the final product, only the first two jobs in the array got disabled. Everything else was enabled.

Fix certificate permissions

(js0505)

had to add the following: Use db

GRANT ALTER ANY SYMMETRIC KEY TO xxx
GRANT VIEW DEFINITION ON CERTIFICATE::cert TO user
GRANT CONTROL ON CERTIFICATE::cert TO user

(js0505)

Certificate permissions did not get moved during migration hence reason for the card.

(Chrissy LeMaire)

@js0505 exactly what I need, thank you!

(js0505)

I have to adjust the script because I already new the certificate name. It is not cert as stated in the script below as well as the user.

(js0505)

also:

select name
from sys.databases
where is_master_key_encrypted_by_server = 1
use <database>
go
open master key decryption by password = '<Password>'
alter master key add encryption by service master key
go

Restore-HallengrenBackup doesn't work with Path character "$"

Hi,

The Restore-HallengrenBackup function fails when trying to restore databases from a file share with character "$" in it's path.

When using Ola Hallengren's backup script to backup databases in an Availability Group, the backup files are stored in a folder with naming format "cluster_name$availability_group_name". The files are also named using naming format "cluster_name$availability_group_name_databasename_FULL_COPY_ONLY_20160627_213000.bak"

Basically, I receive the following error:
File list could not be determined. This is likely due to connectivity issues or tiemouts with the SQL Server, the database version is incorrect, or the SQL Server service account does not have access to the file share. Script terminating.

There's no issue with SQL server timeouts or service accounts access rights.

When I create a different folder (as a test) without a $ character in the same fileshare, copy a few database backups and remove the "$" in the copied backup files and point the Restore-HallengrenBackup function to this test folder on the fileshare restores work flawlessly.

Basically, the "$" character that Hallengren's backup script adds in the backup file path as a replacement of "" breaks your restore script. Is there a way to mitigate this issue?

Start-SqlMigration error

Running Start-SqlMigration on local machine with SQL Server 2014 --> SQL Server 2016. I get an error around the linked server migration that references "unknown key size". The script continues like it is working, even showing messages like it is...but it basically stopped and quit as the error message shows. The process did not do any hard stop (if it should have).

Pastebin of output log.

BackupRestore without SetSourceReadOnly

I cannot find a way to perform Start-SqlMigration with the -BackupRestore method without it trying to set the source databases to read only. I have tried not specifying -SetSourceReadOnly and I have tried -SetSourceReadOnly:$false. How do you perform a SqlMigration without it modifying anything on the source server?

Thanks!

Find-DuplicateIndexes not outputing all of the results in file

Find-DuplicateIndexes - not outputting all of the results in file, only outputs first record for each database that it finds duplicate for. Gridview shows all the results correctly.

(Cláudio Silva)

The main goal is output the drop statements for the selected rows.
Isn't this what is happening?

(Chrissy LeMaire)

That is my understanding as well. @js0505 did you select the ones you wanted to output the T-SQL for?
Can you paste the full command you used?

(js0505)

Yes, I select the ones I wanted for output, however, when there is more than one (Well technically 2 because of the duplicate) in the list per database, it will only output the first click to the file. Command was Find-SqlDuplicateIndex -SqlServer ServerA

Set-DbaDatabaseOwner additional checks

Set-DbaDatabaseOwner needs additional checks for Offline and ReadOnly status, currently throws error and stops cmdlet if the database is in those states. Also check for new owner already being mapped to the db, this also throws an error and stops cmdlet.

Using ReuseFolderStructure causes errors while migrating Database

Specifications

Source: Windows Server 2003
SQL Server Version: 2005

Destination: Windows Server 2008r2
SQL Server Version: 2008

Command: Copy-SqlDatabase -Source SourceName -Destination DestinationName -Verbose -BackupRestore -ReuseFolderstructure -NetworkShare \\fileshare\sql\migration -All -Force

Expected behavior

Database migration should complete

Actual Behavior

Shows whole bunch of errors. Like:

(1) Join-AdminUnc : Cannot process argument transformation on parameter 'filepath'. Cannot convert value to type System.String.
At C:\dbatools\Function\Copy-SqlDatabase.ps1:650 char:45...

(2) WARNING: Restore failed: Restore failed for Server 'Destination'.

(3) Copy-SqlDatabase : Failed to update DatabaseOwnershipChaining for False on something on Destination
At C:\dbatools\Functions\Copy-SqlDatabase.ps1:1039 char:3...

(4) Copy-SqlDatabase : Failed to update Trustworthy to False for something on Destination
At C:\dbatools\Functions\Copy-SqlDatabase.ps1:1039 char:3...

Workaround

Not using -ReuseFolderstructure seems to migrate database properly.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.