PowerShell script to shrink & rebuild your SQL Server databases.

Just change the DB1, DB2, DB3, etc.. to be the actual databases you plan on rebuilding.
Same with the ServerName\InstanceName.

Caveat: Don’t run this script on a regular basis. If your databases keep growing in size, there’s usually a reason for it.

$databases = @('DB1','DB2','DB3')
$watch = New-Object System.Diagnostics.Stopwatch
foreach ($database in $databases) {
 Write-Host "Shrinking - " $database
 Invoke-DbaDbShrink -SqlInstance "ServerName\InstanceName" -Database $database -PercentFreeSpace 10 -FileType Data -StepSize 1GB
 Write-Host $time " done " $database
 Write-Host "Rebuilding " $database
 Invoke-DbaQuery -SqlInstance "ServerName\InstanceName" -Database $database -Query "Exec sp_MSforeachtable 'SET QUOTED_IDENTIFIER ON; ALTER INDEX ALL ON ? REBUILD'"
 $time = $watch.Elapsed.TotalMinutes
 Write-Host $time " - " $database

Be humble.. and grow.

Some people view humility as weakness.
But those who are quick to accept criticism value humility.
They use it to grow.

They realize being humble doesn’t mean they lack self confidence or never stand up for their principles.

It involves recognizing they don’t know everything and they’re willing to learn from others.

Be humble.. and grow.

Longer lines of code are faster.. eh?

I mean, I did have another programmer vehemently argue once long ago that putting more code on one line would make it “run faster.” But of course he was stark raving nuts. Trying to explain to him (with a straight face–which was challenging) how the interpreter or compiler would break that long line apart into discrete one-instruction-per-line statements–essentially identical to the result if he had gone ahead and just made the code readable instead of trying to out-clever the compiler–had no effect on him whatsoever. But I digress.

Craig Tullis on a StackOverflow answer.
Photo by Daniel on Pexels.com

Premature optimization is the root of all evil.. NOT!

We should forget about small efficiencies, say about 97% of the time: premature optimization is the root of all evil. Yet we should not pass up our opportunities in that critical 3%.

Famous computer scientist Donald Knuth

His quote is often clipped down to just “premature optimization is the root of all evil”, but that is NOT TRUE.

Yes, don’t micro-benchmark everything when you begin a project, but please do think ahead. And once you’ve got the program working as intended, then make it faster by profiling and looking for the bottlenecks.

Choose the proper data structures. Array? List? Hashset? Queue? Dictionary? Caching?
Take a few moments and think it over.

How often will this line of code be ran? Do I need to inline it, or pull it out into a separate method?