├── GetPSSQLLib.ps1 ├── PSSQLLib.psd1 ├── PSSQLLib.psm1 └── README.md /GetPSSQLLib.ps1: -------------------------------------------------------------------------------- 1 | # Original file from https://github.com/psget/psget/ 2 | # 3 | # Adjusted to import the PSSQLLib module 4 | 5 | param ( 6 | [string[]]$url = ("https://raw.githubusercontent.com/sanderstad/PSSQLLib/master/PSSQLLib.psm1", "https://raw.githubusercontent.com/sanderstad/PSSQLLib/master/PSSQLLib.psd1") 7 | ) 8 | 9 | function Find-Proxy() { 10 | if ((Test-Path Env:HTTP_PROXY) -Or (Test-Path Env:HTTPS_PROXY)) { 11 | return $true 12 | } 13 | Else { 14 | return $false 15 | } 16 | } 17 | 18 | function Get-Proxy() { 19 | if (Test-Path Env:HTTP_PROXY) { 20 | return $Env:HTTP_PROXY 21 | } 22 | ElseIf (Test-Path Env:HTTPS_PROXY) { 23 | return $Env:HTTPS_PROXY 24 | } 25 | } 26 | 27 | function Get-File { 28 | [CmdletBinding()] 29 | param ( 30 | [Parameter(Mandatory=$true)] 31 | [String] $Url, 32 | 33 | [Parameter(Mandatory=$true)] 34 | [String] $SaveToLocation 35 | ) 36 | $command = (Get-Command Invoke-WebRequest -ErrorAction SilentlyContinue) 37 | if($command -ne $null) { 38 | if (Find-Proxy) { 39 | $proxy = Get-Proxy 40 | Write-Host "Proxy detected" 41 | Write-Host "Using proxy address $proxy" 42 | Invoke-WebRequest -Uri $Url -OutFile $SaveToLocation -Proxy $proxy 43 | } 44 | else { 45 | Invoke-WebRequest -Uri $Url -OutFile $SaveToLocation 46 | } 47 | } 48 | else { 49 | $client = (New-Object Net.WebClient) 50 | $client.UseDefaultCredentials = $true 51 | if (Find-Proxy) { 52 | $proxy = Get-Proxy 53 | Write-Host "Proxy detected" 54 | Write-Host "Using proxy address $proxy" 55 | $webproxy = new-object System.Net.WebProxy 56 | $webproxy.Address = $proxy 57 | $client.proxy = $webproxy 58 | } 59 | $client.DownloadFile($Url, $SaveToLocation) 60 | } 61 | } 62 | 63 | function Install-PSSQLLib { 64 | 65 | param ( 66 | [string[]] 67 | # URL to the respository to download PSSQLLib from 68 | $url 69 | ) 70 | 71 | $ModulePaths = @($env:PSModulePath -split ';') 72 | # $PSSQLLibDestinationModulePath is mostly needed for testing purposes, 73 | if ((Test-Path -Path Variable:PSSQLLibDestinationModulePath) -and $PSSQLLibDestinationModulePath) { 74 | $Destination = $PSSQLLibDestinationModulePath 75 | if ($ModulePaths -notcontains $Destination) { 76 | Write-Warning 'PSSQLLib install destination is not included in the PSModulePath environment variable' 77 | } 78 | } 79 | else { 80 | $ExpectedUserModulePath = Join-Path -Path ([Environment]::GetFolderPath('MyDocuments')) -ChildPath WindowsPowerShell\Modules 81 | $Destination = $ModulePaths | Where-Object { $_ -eq $ExpectedUserModulePath } 82 | if (-not $Destination) { 83 | $Destination = $ModulePaths | Select-Object -Index 0 84 | } 85 | } 86 | New-Item -Path ($Destination + "\PSSQLLib\") -ItemType Directory -Force | Out-Null 87 | 88 | Write-Host ('Downloading PSSQLLib from {0}' -f $url[0]) 89 | Get-File -Url $url[0] -SaveToLocation "$Destination\PSSQLLib\PSSQLLib.psm1" 90 | 91 | Write-Host ('Downloading PSSQLLib from {0}' -f $url[1]) 92 | Get-File -Url $url[1] -SaveToLocation "$Destination\PSSQLLib\PSSQLLib.psd1" 93 | 94 | $executionPolicy = (Get-ExecutionPolicy) 95 | $executionRestricted = ($executionPolicy -eq "Restricted") 96 | if ($executionRestricted) { 97 | Write-Warning @" 98 | Your execution policy is $executionPolicy, this means you will not be able import or use any scripts including modules. 99 | To fix this change your execution policy to something like RemoteSigned. 100 | PS> Set-ExecutionPolicy RemoteSigned 101 | For more information execute: 102 | PS> Get-Help about_execution_policies 103 | "@ 104 | } 105 | 106 | if (!$executionRestricted) { 107 | # ensure PSSQLLib is imported from the location it was just installed to 108 | Import-Module -Name $Destination\PSSQLLib 109 | } 110 | Write-Host "PSSQLLib is installed and ready to use" -Foreground Green 111 | 112 | } 113 | 114 | Install-PSSQLLib -Url $url 115 | -------------------------------------------------------------------------------- /PSSQLLib.psd1: -------------------------------------------------------------------------------- 1 | # 2 | # Module manifest for module 'PSSQLLib' 3 | # 4 | # Generated by: Sander Stad 5 | # 6 | 7 | @{ 8 | 9 | # Script module or binary module file associated with this manifest. 10 | RootModule = 'PSSQLLib' 11 | 12 | # Version number of this module. 13 | ModuleVersion = '1.5.1' 14 | 15 | # ID used to uniquely identify this module 16 | GUID = '51853022-3931-4e43-936a-02739a1bb6d2' 17 | 18 | # Author of this module 19 | Author = 'Sander Stad' 20 | 21 | # Company or vendor of this module 22 | CompanyName = 'SQLStad' 23 | 24 | # Copyright statement for this module 25 | Copyright = 'Sander Stad (SQLStad)' 26 | 27 | # Description of the functionality provided by this module 28 | # Description = '' 29 | 30 | # Minimum version of the Windows PowerShell engine required by this module 31 | PowerShellVersion = '3.0' 32 | 33 | # Name of the Windows PowerShell host required by this module 34 | # PowerShellHostName = '' 35 | 36 | # Minimum version of the Windows PowerShell host required by this module 37 | # PowerShellHostVersion = '' 38 | 39 | # Minimum version of Microsoft .NET Framework required by this module 40 | # DotNetFrameworkVersion = '' 41 | 42 | # Minimum version of the common language runtime (CLR) required by this module 43 | # CLRVersion = '' 44 | 45 | # Processor architecture (None, X86, Amd64) required by this module 46 | # ProcessorArchitecture = '' 47 | 48 | # Modules that must be imported into the global environment prior to importing this module 49 | # RequiredModules = @() 50 | 51 | # Assemblies that must be loaded prior to importing this module 52 | # RequiredAssemblies = @() 53 | 54 | # Script files (.ps1) that are run in the caller's environment prior to importing this module. 55 | # ScriptsToProcess = @() 56 | 57 | # Type files (.ps1xml) to be loaded when importing this module 58 | # TypesToProcess = @() 59 | 60 | # Format files (.ps1xml) to be loaded when importing this module 61 | # FormatsToProcess = @() 62 | 63 | # Modules to import as nested modules of the module specified in RootModule/ModuleToProcess 64 | # NestedModules = @() 65 | 66 | # Functions to export from this module 67 | FunctionsToExport = '*' 68 | 69 | # Cmdlets to export from this module 70 | CmdletsToExport = '*' 71 | 72 | # Variables to export from this module 73 | VariablesToExport = '*' 74 | 75 | # Aliases to export from this module 76 | AliasesToExport = '*' 77 | 78 | # List of all modules packaged with this module 79 | # ModuleList = @() 80 | 81 | # List of all files packaged with this module 82 | # FileList = @() 83 | 84 | # Private data to pass to the module specified in RootModule/ModuleToProcess 85 | # PrivateData = '' 86 | 87 | # HelpInfo URI of this module 88 | # HelpInfoURI = '' 89 | 90 | # Default prefix for commands exported from this module. Override the default prefix using Import-Module -Prefix. 91 | # DefaultCommandPrefix = '' 92 | 93 | } 94 | 95 | -------------------------------------------------------------------------------- /PSSQLLib.psm1: -------------------------------------------------------------------------------- 1 | ################################################################################ 2 | # Written by Sander Stad, SQLStad.nl 3 | # 4 | # (c) 2016, SQLStad.nl. All rights reserved. 5 | # 6 | # For more scripts and sample code, check out http://www.SQLStad.nl 7 | # 8 | # You may alter this code for your own *non-commercial* purposes (e.g. in a 9 | # for-sale commercial tool). Use in your own environment is encouraged. 10 | # You may republish altered code as long as you include this copyright and 11 | # give due credit, but you must obtain prior permission before blogging 12 | # this code. 13 | # 14 | # THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF 15 | # ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED 16 | # TO THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A 17 | # PARTICULAR PURPOSE. 18 | # 19 | # Changelog: 20 | # v1.0: 21 | # Initial version 22 | # v1.1: 23 | # Added several functions for hosts 24 | # v1.2: 25 | # Added functionality to get the host system information 26 | # Cleaned up code, make it more readable 27 | # Changed parameters to be consistent throughout functions 28 | # v1.3: 29 | # Added extra error catching 30 | # v1.3.1: 31 | # Added function for retrieving disk latencies 32 | # v1.3.2: 33 | # Added functionality for retrieving backups 34 | # v1.3.3: 35 | # Added functionality for retrieving the system uptime 36 | # Added functionality for retrieving the instance uptime 37 | # v1.4.0 38 | # Added structures to the functions 39 | # v1.4.1 40 | # Added functionality for using ports connecting to SQL Server 41 | # Changed the try/catch procedures to catch more error and work more efficiently 42 | # v1.5 43 | # Added functionality to export database objects to .sql script files 44 | # Changed the error messages in the functions to be more descriptive 45 | # v1.5.1 46 | # Added functionality to export SQL Server objects to .sql script files 47 | ################################################################################ 48 | 49 | function Get-HostHarddisk 50 | { 51 | <# 52 | .SYNOPSIS 53 | Checks the host's harddisks 54 | .DESCRIPTION 55 | The function return the data of all the drives with size, available space, percentage used etc 56 | .PARAMETER hst 57 | This is the host that needs to be connected 58 | .EXAMPLE 59 | Get-HostHarddisk "SQL01" 60 | .EXAMPLE 61 | Get-HostHarddisk -hst "SQL01" 62 | .INPUTS 63 | .OUTPUTS 64 | System.Array 65 | .NOTES 66 | .LINK 67 | #> 68 | [Cmdletbinding()] 69 | param 70 | ( 71 | [Parameter(Mandatory = $true, Position=1)] 72 | [ValidateNotNullOrEmpty()] 73 | [string]$hst = $null 74 | ) 75 | 76 | try 77 | { 78 | # Get the data 79 | $drives= Get-WmiObject -Class Win32_LogicalDisk -Computername $hst -Errorvariable errorvar | Where {$_.drivetype -eq 3} 80 | 81 | # Create the result array 82 | $result = @() 83 | 84 | # Get the results 85 | $result = $drives | Select -property ` 86 | @{N="Disk";E={$_.DeviceID}},VolumeName, ` 87 | @{N="FreeSpaceMB";E={"{0:N2}" -f ($_.Freespace/1Mb)}}, ` 88 | @{N="SizeMB";E={"{0:N2}" -f ($_.Size/1Mb)}}, ` 89 | @{N="PercentageUsed";E={"{0:N2}" -f (($_.Size - $_.FreeSpace) / $_.Size * 100)}} 90 | 91 | return $result 92 | } 93 | catch 94 | { 95 | $errorMessage = $_.Exception.Message 96 | $line = $_.InvocationInfo.ScriptLineNumber 97 | $script_name = $_.InvocationInfo.ScriptName 98 | Write-Host "Error: Occurred on line $line in script $script_name." -ForegroundColor Red 99 | Write-Host "Error: $ErrorMessage" -ForegroundColor Red 100 | } 101 | } 102 | 103 | function Get-HostHardware 104 | { 105 | <# 106 | .SYNOPSIS 107 | Checks the host's hardware 108 | .DESCRIPTION 109 | The function return the data of hardware in de host like number of processors 110 | manufacturer, current timezone etc 111 | .PARAMETER hst 112 | This is the host that needs to be connected 113 | .EXAMPLE 114 | Get-HostHardware "SQL01" 115 | .EXAMPLE 116 | Get-HostHardware -hst "SQL01" 117 | .INPUTS 118 | .OUTPUTS 119 | System.Array 120 | .NOTES 121 | .LINK 122 | #> 123 | [Cmdletbinding()] 124 | param 125 | ( 126 | [Parameter(Mandatory = $true, Position=1)] 127 | [ValidateNotNullOrEmpty()] 128 | [string]$hst = $null 129 | ) 130 | 131 | try 132 | { 133 | # Get the data 134 | $computer = Get-Wmiobject -Class win32_computersystem -Computername $hst -Errorvariable errorvar 135 | 136 | $result = @() 137 | 138 | # Get the result 139 | $result = $computer | Select Description,NumberOfLogicalProcessors,NumberOfProcessors, ` 140 | @{N="TotalPhysicalMemoryGB";E={"{0:N2}" -f ($_.TotalPhysicalMemory/1Gb)}}, ` 141 | Model,Manufacturer,PartOfDomain,CurrentTimeZone,DaylightInEffect 142 | 143 | # Return the result 144 | return $result 145 | } 146 | catch 147 | { 148 | $errorMessage = $_.Exception.Message 149 | $line = $_.InvocationInfo.ScriptLineNumber 150 | $script_name = $_.InvocationInfo.ScriptName 151 | Write-Host "Error: Occurred on line $line in script $script_name." -ForegroundColor Red 152 | Write-Host "Error: $ErrorMessage" -ForegroundColor Red 153 | } 154 | } 155 | 156 | function Get-HostOperatingSystem 157 | { 158 | <# 159 | .SYNOPSIS 160 | Checks the host's OS 161 | .DESCRIPTION 162 | The function return the data of OS in de host like the architecture, 163 | the OS language, the version etc 164 | .PARAMETER hst 165 | This is the host that needs to be connected 166 | .EXAMPLE 167 | Get-HostOperatingSystems "SQL01" 168 | .EXAMPLE 169 | Get-HostOperatingSystems -hst "SQL01" 170 | .INPUTS 171 | .OUTPUTS 172 | System.Array 173 | .NOTES 174 | .LINK 175 | #> 176 | [Cmdletbinding()] 177 | param 178 | ( 179 | [Parameter(Mandatory = $true, Position=1)] 180 | [ValidateNotNullOrEmpty()] 181 | [string]$hst = $null 182 | ) 183 | 184 | try 185 | { 186 | # Get the data 187 | $os = Get-WmiObject -Class win32_operatingsystem -Computername $hst -Errorvariable errorvar 188 | 189 | $result = @() 190 | 191 | # Get the results 192 | $result = $os | Select ` 193 | OSArchitecture,OSLanguage,OSProductSuite,OSType,BuildNumbe,` 194 | BuildType,Version,WindowsDirectory,PlusVersionNumber,` 195 | @{N="FreePhysicalMemoryMB";E={"{0:N2}" -f ($_.FreePhysicalMemory / 1Mb)}},` 196 | @{N="FreeSpaceInPagingFilesMB";E={"{0:N2}" -f ($_.FreeSpaceInPagingFiles)}},` 197 | @{N="FreeVirtualMemoryMB";E={"{0:N2}" -f ($_.FreeVirtualMemory)}},` 198 | PAEEnabled,ServicePackMajorVersion,ServicePackMinorVersion 199 | 200 | #return the result 201 | return $result 202 | } 203 | catch 204 | { 205 | $errorMessage = $_.Exception.Message 206 | $line = $_.InvocationInfo.ScriptLineNumber 207 | $script_name = $_.InvocationInfo.ScriptName 208 | Write-Host "Error: Occurred on line $line in script $script_name." -ForegroundColor Red 209 | Write-Host "Error: $ErrorMessage" -ForegroundColor Red 210 | } 211 | 212 | } 213 | 214 | function Get-HostSQLServerServices 215 | { 216 | <# 217 | .SYNOPSIS 218 | Get the SQL Server services 219 | .DESCRIPTION 220 | The function return all the services present on the server regarding SQL Server 221 | .PARAMETER hst 222 | This is the host that needs to be connected 223 | .EXAMPLE 224 | Get-HostSQLServerServices "SQL01" 225 | .EXAMPLE 226 | Get-HostSQLServerService -hst "SQL01" 227 | .INPUTS 228 | .OUTPUTS 229 | System.Array 230 | .NOTES 231 | .LINK 232 | #> 233 | [Cmdletbinding()] 234 | param 235 | ( 236 | [Parameter(Mandatory = $true, Position=1)] 237 | [ValidateNotNullOrEmpty()] 238 | [string]$hst = $null 239 | ) 240 | 241 | try 242 | { 243 | return Get-WmiObject win32_Service -Computer $hst | where {$_.DisplayName -match "SQL Server"} | ` 244 | select SystemName, DisplayName, Name, State, Status, StartMode, StartName 245 | } 246 | catch 247 | { 248 | $errorMessage = $_.Exception.Message 249 | $line = $_.InvocationInfo.ScriptLineNumber 250 | $script_name = $_.InvocationInfo.ScriptName 251 | Write-Host "Error: Occurred on line $line in script $script_name." -ForegroundColor Red 252 | Write-Host "Error: $ErrorMessage" -ForegroundColor Red 253 | } 254 | } 255 | 256 | function Get-HostSystemInformation() 257 | { 258 | <# 259 | .SYNOPSIS 260 | Get the system information of the host 261 | .DESCRIPTION 262 | Select information from the system like the domain, manufacturer, model etc. 263 | .PARAMETER hst 264 | This is the host that needs to be connected 265 | .EXAMPLE 266 | Get-HostSystemInformation "SQL01" 267 | .EXAMPLE 268 | Get-HostSystemInformation -hst "SQL01" 269 | .INPUTS 270 | .OUTPUTS 271 | System.Array 272 | .NOTES 273 | .LINK 274 | #> 275 | [Cmdletbinding()] 276 | param( 277 | [Parameter(Mandatory = $true, Position=1)] 278 | [ValidateNotNullOrEmpty()] 279 | [string]$hst = $null 280 | ) 281 | 282 | try 283 | { 284 | $data = Get-WmiObject -class "Win32_ComputerSystem" -Namespace "root\CIMV2" -ComputerName $hst 285 | 286 | $result = @() 287 | $result = $data | Select ` 288 | Name,Domain,Manufacturer,Model, ` 289 | NumberOfLogicalProcessors,NumberOfProcessors,LastLoadInfo, ` 290 | @{Name='TotalPhysicalMemoryMB';Expression={[math]::round(($_.TotalPhysicalMemory / 1024 / 1024))}} 291 | 292 | 293 | return $result 294 | 295 | } 296 | catch 297 | { 298 | $errorMessage = $_.Exception.Message 299 | $line = $_.InvocationInfo.ScriptLineNumber 300 | $script_name = $_.InvocationInfo.ScriptName 301 | Write-Host "Error: Occurred on line $line in script $script_name." -ForegroundColor Red 302 | Write-Host "Error: $ErrorMessage" -ForegroundColor Red 303 | } 304 | 305 | } 306 | 307 | function Get-HostUptime 308 | { 309 | <# 310 | .SYNOPSIS 311 | Get the uptime of the host 312 | .DESCRIPTION 313 | The script will retrieve the boot time and local time. 314 | Based on the start time the uptime will be calculated. 315 | .PARAMETER hst 316 | This is the instance that needs to be connected 317 | .EXAMPLE 318 | Get-HostUptime "SQL01" 319 | .EXAMPLE 320 | Get-HostUptime -hst "SQL01" 321 | .INPUTS 322 | .OUTPUTS 323 | System.Array 324 | .NOTES 325 | .LINK 326 | #> 327 | [Cmdletbinding()] 328 | param 329 | ( 330 | [Parameter(Mandatory = $true, Position=1)] 331 | [ValidateNotNullOrEmpty()] 332 | [string]$hst = $env:COMPUTERNAME 333 | , [Parameter(Mandatory = $false, Position=2)] 334 | $cred = [System.Management.Automation.PSCredential]::Empty 335 | ) 336 | 337 | try 338 | { 339 | $os = Get-WmiObject win32_operatingsystem -ComputerName $hst -ErrorAction Stop -Credential $cred 340 | 341 | $result = @() 342 | 343 | $bootTime = $os.ConvertToDateTime($os.LastBootUpTime) 344 | $uptime = $os.ConvertToDateTime($os.LocalDateTime) - $bootTime 345 | 346 | $uptimeString = $uptime.Days.ToString() + " Day(s) " + $uptime.Hours.ToString() + ":" + $uptime.Minutes.ToString() + ":" + $uptime.Seconds.ToString() 347 | 348 | $result = $os | Select -property ` 349 | @{N="BootTime";E={$bootTime}}, ` 350 | @{N="Uptime";E={$uptimeString}} 351 | 352 | 353 | return $result 354 | } 355 | catch [Exception] 356 | { 357 | $errorMessage = $_.Exception.Message 358 | $line = $_.InvocationInfo.ScriptLineNumber 359 | $script_name = $_.InvocationInfo.ScriptName 360 | Write-Host "Error: Occurred on line $line in script $script_name." -ForegroundColor Red 361 | Write-Host "Error: $ErrorMessage" -ForegroundColor Red 362 | } 363 | 364 | } 365 | 366 | ################################################## 367 | 368 | function Get-SQLAgentJobs 369 | { 370 | <# 371 | .SYNOPSIS 372 | Returns the SQL Server jobs 373 | .DESCRIPTION 374 | The function return all the jobs present in the SQL Server with information 375 | like the jobtype, enabled or not, date created, last run date etc. 376 | .PARAMETER instance 377 | This is the instance that needs to be connected 378 | .PARAMETER port 379 | This is the port of the instance that needs to be used 380 | .EXAMPLE 381 | Get-SQLServerJobs "SQL01" 382 | .EXAMPLE 383 | Get-SQLServerJobs "SQL01\INST01" 384 | .EXAMPLE 385 | Get-SQLServerJobs "SQL01\INST01" 4321 386 | .EXAMPLE 387 | Get-SQLServerJobs -inst "SQL01\INST01" 388 | .EXAMPLE 389 | Get-SQLServerJobs -inst "SQL01\INST01" -port 4321 390 | .INPUTS 391 | .OUTPUTS 392 | System.Array 393 | .NOTES 394 | .LINK 395 | #> 396 | [Cmdletbinding()] 397 | param 398 | ( 399 | [Parameter(Mandatory = $true, Position=1)] 400 | [ValidateNotNullOrEmpty()] 401 | [string]$inst = $null, 402 | [Parameter(Mandatory = $false, Position=2)] 403 | [string]$port = '1433' 404 | ) 405 | 406 | 407 | # Check if assembly is loaded 408 | Load-Assembly -name 'Microsoft.SqlServer.SMO' 409 | 410 | # Create the server object and retrieve the information 411 | try{ 412 | $server = New-Object ('Microsoft.SqlServer.Management.Smo.Server') "$inst,$port" 413 | 414 | # Get the jobs 415 | $server.JobServer.Jobs 416 | 417 | # Create the result array 418 | $result = @() 419 | 420 | # Get the results 421 | $result = $jobs | Select ` 422 | Name,JobType,IsEnabled,DateCreated,DateLastModified,LastRunDate,` 423 | LastRunOutcome,NextRunDate,OwnerLoginName,Category | Sort-Object Name 424 | 425 | # Return the result 426 | return $result 427 | } 428 | catch [Exception] 429 | { 430 | $errorMessage = $_.Exception.Message 431 | $line = $_.InvocationInfo.ScriptLineNumber 432 | $script_name = $_.InvocationInfo.ScriptName 433 | Write-Host "Error: Occurred on line $line in script $script_name." -ForegroundColor Red 434 | Write-Host "Error: $ErrorMessage" -ForegroundColor Red 435 | } 436 | 437 | } 438 | 439 | function Get-SQLConfiguration 440 | { 441 | <# 442 | .SYNOPSIS 443 | Get the contents of the configuration of the instance 444 | .DESCRIPTION 445 | The script will connect to the instance and execute a query to get the 446 | configuration settings. It wil return a table with the configurations. 447 | .PARAMETER instance 448 | This is the instance that needs to be connected 449 | .PARAMETER port 450 | This is the port of the instance that needs to be used 451 | .EXAMPLE 452 | Get-SQLConfiguration "SQL01" 453 | .EXAMPLE 454 | Get-SQLConfiguration "SQL01\INST01" 455 | .EXAMPLE 456 | Get-SQLConfiguration "SQL01\INST01" 4321 457 | .EXAMPLE 458 | Get-SQLConfiguration -inst "SQL01\INST01" 459 | .EXAMPLE 460 | Get-SQLConfiguration -inst "SQL01\INST01" -port 4321 461 | .INPUTS 462 | .OUTPUTS 463 | System.Array 464 | .NOTES 465 | .LINK 466 | #> 467 | [Cmdletbinding()] 468 | param 469 | ( 470 | [Parameter(Mandatory = $true, Position=1)] 471 | [ValidateNotNullOrEmpty()] 472 | [string]$inst = $null, 473 | [Parameter(Mandatory = $false, Position=2)] 474 | [string]$port = '1433' 475 | ) 476 | 477 | # Check if assembly is loaded 478 | Load-Assembly -name 'Microsoft.SqlServer.SMO' 479 | 480 | # Create the server object and retrieve the information 481 | try{ 482 | 483 | $server = New-Object ('Microsoft.SqlServer.Management.Smo.Server') "$inst,$port" 484 | 485 | # Define the array 486 | $result = @() 487 | 488 | # Get the configurations 489 | $configuration = $server.Configuration 490 | 491 | # Get all the properties 492 | $result = $configuration.Properties 493 | 494 | # Return the result 495 | return $result 496 | } 497 | catch [Exception] 498 | { 499 | $errorMessage = $_.Exception.Message 500 | $line = $_.InvocationInfo.ScriptLineNumber 501 | $script_name = $_.InvocationInfo.ScriptName 502 | Write-Host "Error: Occurred on line $line in script $script_name." -ForegroundColor Red 503 | Write-Host "Error: $ErrorMessage" -ForegroundColor Red 504 | } 505 | 506 | 507 | } 508 | 509 | function Get-SQLDatabaseFiles 510 | { 511 | <# 512 | .SYNOPSIS 513 | Get the database files for each database 514 | .DESCRIPTION 515 | The function return all the database files from all databases 516 | .PARAMETER instance 517 | This is the instance that needs to be connected 518 | .PARAMETER port 519 | This is the port of the instance that needs to be used 520 | .PARAMETER dbfilter 521 | This is used to return only show details on certain databases 522 | .EXAMPLE 523 | Get-Get-SQLDatabaseFiles "SQL01" 524 | .EXAMPLE 525 | Get-Get-SQLDatabaseFiles "SQL01\INST01" 526 | .EXAMPLE 527 | Get-Get-SQLDatabaseFiles "SQL01\INST01" 4321 528 | .EXAMPLE 529 | Get-Get-SQLDatabaseFiles -inst "SQL01\INST01" 530 | .EXAMPLE 531 | Get-Get-SQLDatabaseFiles -inst "SQL01\INST01" -port 4321 532 | .INPUTS 533 | .OUTPUTS 534 | System.Array 535 | .NOTES 536 | .LINK 537 | #> 538 | [Cmdletbinding()] 539 | param 540 | ( 541 | [Parameter(Mandatory = $true, Position=1)] 542 | [ValidateNotNullOrEmpty()] 543 | [string]$inst = $null, 544 | [Parameter(Mandatory = $false, Position=2)] 545 | [string]$port = '1433' 546 | ) 547 | 548 | # Check if assembly is loaded 549 | Load-Assembly -name 'Microsoft.SqlServer.SMO' 550 | 551 | # Create the server object and retrieve the information 552 | try{ 553 | $server = New-Object ('Microsoft.SqlServer.Management.Smo.Server') "$inst,$port" 554 | 555 | # Define the array 556 | $dataFiles = @() 557 | $logFiles = @() 558 | $result = @() 559 | # Get all the databases 560 | $databases = $server.Databases 561 | 562 | # Loop through all the databases 563 | foreach($database in $databases) 564 | { 565 | try{ 566 | # Get the filegroups for the database 567 | $filegroups = $database.FileGroups 568 | 569 | # Loop through all the filegroups 570 | foreach($filegroup in $filegroups) 571 | { 572 | # Get all the data files from the filegroup 573 | $files = $filegroup.Files 574 | 575 | # Loop through all the data files 576 | foreach($file in $files) 577 | { 578 | $result += $file | Select ` 579 | @{Name="DatabaseName"; Expression={$database.Name}}, Name, ` 580 | @{Name="FileType";Expression={"ROWS"}}, ` 581 | @{Name="Directory"; Expression={$file.FileName | Split-Path -Parent}}, ` 582 | @{Name="FileName"; Expression={$file.FileName | Split-Path -Leaf}}, ` 583 | Growth, GrowthType, Size, UsedSpace 584 | } 585 | } 586 | 587 | # Get all the data files from the filegroup 588 | $files = $database.LogFiles 589 | 590 | # Loop through all the log files 591 | foreach($file in $files) 592 | { 593 | $result += $file | Select ` 594 | @{Name="DatabaseName"; Expression={$database.Name}}, Name, ` 595 | @{Name="FileType";Expression={"LOG"}}, ` 596 | @{Name="Directory"; Expression={$file.FileName | Split-Path -Parent}}, ` 597 | @{Name="FileName"; Expression={$file.FileName | Split-Path -Leaf}}, ` 598 | Growth, GrowthType, Size, UsedSpace 599 | } 600 | } 601 | catch{ 602 | 603 | } 604 | 605 | } 606 | 607 | return $result 608 | } 609 | catch [Exception] 610 | { 611 | $errorMessage = $_.Exception.Message 612 | $line = $_.InvocationInfo.ScriptLineNumber 613 | $script_name = $_.InvocationInfo.ScriptName 614 | Write-Host "Error: Occurred on line $line in script $script_name." -ForegroundColor Red 615 | Write-Host "Error: $ErrorMessage" -ForegroundColor Red 616 | } 617 | 618 | 619 | } 620 | 621 | function Get-SQLDatabasePrivileges 622 | { 623 | <# 624 | .SYNOPSIS 625 | Gets the users in the database and looks up the roles 626 | .DESCRIPTION 627 | The function return all the database users with their roles in the database 628 | .PARAMETER instance 629 | This is the instance that needs to be connected 630 | .PARAMETER port 631 | This is the port of the instance that needs to be used 632 | .EXAMPLE 633 | Get-SQLDatabasePrivileges "SQL01" 634 | .EXAMPLE 635 | Get-SQLDatabasePrivileges "SQL01\INST01" 636 | .EXAMPLE 637 | Get-SQLDatabasePrivileges "SQL01\INST01" 4321 638 | .EXAMPLE 639 | Get-SQLDatabasePrivileges -inst "SQL01\INST01" 640 | .EXAMPLE 641 | Get-SQLDatabasePrivileges -inst "SQL01\INST01" -port 4321 642 | .INPUTS 643 | .OUTPUTS 644 | System.Array 645 | .NOTES 646 | .LINK 647 | #> 648 | [Cmdletbinding()] 649 | param 650 | ( 651 | [Parameter(Mandatory = $true, Position=1)] 652 | [ValidateNotNullOrEmpty()] 653 | [string]$inst = $null, 654 | [Parameter(Mandatory = $false, Position=2)] 655 | [string]$port = '1433' 656 | ) 657 | 658 | # Check if assembly is loaded 659 | Load-Assembly -name 'Microsoft.SqlServer.SMO' 660 | 661 | # Create the server object and retrieve the information 662 | try{ 663 | $server = New-Object ('Microsoft.SqlServer.Management.Smo.Server') "$inst,$port" 664 | 665 | # Create the result array 666 | $result = @() 667 | 668 | # Create the memberRoles array 669 | $userRoles = @() 670 | 671 | # Get all the databases 672 | $databases = $server.Databases 673 | 674 | # Loop through the databases 675 | foreach($database in $databases) 676 | { 677 | # Get all the logins 678 | $users = $database.Users 679 | 680 | # Get all the roles 681 | $roles = $database.Roles 682 | 683 | # Loop through the logins 684 | foreach($user in $users) 685 | { 686 | # Check if user is not a system user 687 | if( 688 | ($user.Name -ne "dbo") ` 689 | -and ($user.Name -notlike "##*") ` 690 | -and ($user.Name -ne "INFORMATION_SCHEMA") ` 691 | -and ($user.Name -ne "sys") ` 692 | -and ($user.Name -ne "guest")) 693 | { 694 | 695 | # Loop through the roles 696 | foreach($role in $roles) 697 | { 698 | # Get all the members of the role 699 | $roleMembers = $role.EnumMembers() 700 | 701 | # Check if the login is in the list 702 | if($roleMembers -contains $user.Name) 703 | { 704 | $userRoles += $role.Name 705 | } 706 | } 707 | 708 | # Combine the results 709 | $result += $database | Select ` 710 | @{N="DatabaseName";E={$database.Name}},` 711 | @{N="UserName";E={$user.Name}},` 712 | @{N="UserType"; E={$user.LoginType}},` 713 | @{N="DatabaseRoles";E={([string]::Join(",", $userRoles))}} 714 | } 715 | 716 | # Clear the array 717 | $userRoles = @() 718 | } 719 | } 720 | 721 | return $result 722 | } 723 | catch [Exception] 724 | { 725 | $errorMessage = $_.Exception.Message 726 | $line = $_.InvocationInfo.ScriptLineNumber 727 | $script_name = $_.InvocationInfo.ScriptName 728 | Write-Host "Error: Occurred on line $line in script $script_name." -ForegroundColor Red 729 | Write-Host "Error: $ErrorMessage" -ForegroundColor Red 730 | } 731 | } 732 | 733 | function Get-SQLDatabases 734 | { 735 | <# 736 | .SYNOPSIS 737 | Get the SQL Server database settings 738 | .DESCRIPTION 739 | This function gets the settings of the prent databases and returns 740 | the data in the form of a table. 741 | .PARAMETER instance 742 | This is the instance that needs to be connected 743 | .PARAMETER port 744 | This is the port of the instance that needs to be used 745 | .EXAMPLE 746 | Get-Get-SQLDatabases "SQL01" 747 | .EXAMPLE 748 | Get-Get-SQLDatabases "SQL01\INST01" 749 | .EXAMPLE 750 | Get-Get-SQLDatabases "SQL01\INST01" 4321 751 | .EXAMPLE 752 | Get-Get-SQLDatabases -inst "SQL01\INST01" 753 | .EXAMPLE 754 | Get-Get-SQLDatabases -inst "SQL01\INST01" -port 4321 755 | .INPUTS 756 | .OUTPUTS 757 | System.Array 758 | .NOTES 759 | .LINK 760 | #> 761 | [Cmdletbinding()] 762 | param 763 | ( 764 | [Parameter(Mandatory = $true, Position=1)] 765 | [ValidateNotNullOrEmpty()] 766 | [string]$inst = $null, 767 | [Parameter(Mandatory = $false, Position=2)] 768 | [string]$port = '1433' 769 | ) 770 | 771 | # Check if assembly is loaded 772 | Load-Assembly -name 'Microsoft.SqlServer.SMO' 773 | 774 | # Create the server object and retrieve the information 775 | try{ 776 | $server = New-Object ('Microsoft.SqlServer.Management.Smo.Server') "$inst,$port" 777 | 778 | # Define the array 779 | $result = @() 780 | # Get all the databases 781 | $databases = $server.Databases 782 | 783 | # Get the properties of each database 784 | $result = $databases | Select ` 785 | ID,Name,AutoClose,AutoCreateIncrementalStatisticsEnabled,` 786 | AutoCreateStatisticsEnabled,AutoShrink,AutoUpdateStatisticsAsync,AutoUpdateStatisticsEnabled,` 787 | AvailabilityGroupName,CloseCursorsOnCommitEnabled,Collation,` 788 | CompatibilityLevel,CreateDate,DataSpaceUsage,` 789 | DelayedDurability,EncryptionEnabled,HasDatabaseEncryptionKey,HasFileInCloud,HasFullBackup,` 790 | IndexSpaceUsage,IsDbSecurityAdmin,IsFullTextEnabled,IsManagementDataWarehouse,IsMirroringEnabled,` 791 | LastBackupDate,LastDifferentialBackupDate,LastLogBackupDate,` 792 | Owner,PageVerify,PolicyHealthState,PrimaryFilePath,ReadOnly,` 793 | RecoveryModel,RecursiveTriggersEnabled,Size,SnapshotIsolationState,SpaceAvailable,` 794 | Status,TargetRecoveryTime,Trustworthy,UserAccess,UserName,Version 795 | 796 | # Return the result 797 | return $result 798 | } 799 | catch [Exception] 800 | { 801 | $errorMessage = $_.Exception.Message 802 | $line = $_.InvocationInfo.ScriptLineNumber 803 | $script_name = $_.InvocationInfo.ScriptName 804 | Write-Host "Error: Occurred on line $line in script $script_name." -ForegroundColor Red 805 | Write-Host "Error: $ErrorMessage" -ForegroundColor Red 806 | } 807 | 808 | 809 | } 810 | 811 | function Get-SQLDatabaseUsers 812 | { 813 | <# 814 | .SYNOPSIS 815 | Get the database users 816 | .DESCRIPTION 817 | The function returns all the database users present 818 | .PARAMETER instance 819 | This is the instance that needs to be connected 820 | .PARAMETER port 821 | This is the port of the instance that needs to be used 822 | .PARAMETER dbfilter 823 | This is used to return only show details on certain databases 824 | .EXAMPLE 825 | Get-SQLDatabaseUsers "SQL01" 826 | .EXAMPLE 827 | Get-SQLDatabaseUsers "SQL01\INST01" 828 | .EXAMPLE 829 | Get-SQLDatabaseUsers "SQL01\INST01" 4321 830 | .EXAMPLE 831 | Get-SQLDatabaseUsers -inst "SQL01\INST01" 832 | .EXAMPLE 833 | Get-SQLDatabaseUsers -inst "SQL01\INST01" -port 4321 834 | .EXAMPLE 835 | Get-SQLDatabaseUsers -inst "SQL01\INST01" -port 4321 -dbfilter "tempdb,msdb" 836 | .INPUTS 837 | .OUTPUTS 838 | System.Array 839 | .NOTES 840 | .LINK 841 | #> 842 | [Cmdletbinding()] 843 | param 844 | ( 845 | [Parameter(Mandatory = $true, Position=1)] 846 | [ValidateNotNullOrEmpty()] 847 | [string]$inst = $null, 848 | [Parameter(Mandatory = $false, Position=2)] 849 | [string]$port = '1433' 850 | , [Parameter(Mandatory = $false, Position=3)] 851 | [ValidateNotNullOrEmpty()] 852 | [string]$dbfilter = $null 853 | ) 854 | 855 | # Check if assembly is loaded 856 | Load-Assembly -name 'Microsoft.SqlServer.SMO' 857 | 858 | # Create the server object and retrieve the information 859 | try{ 860 | $server = New-Object ('Microsoft.SqlServer.Management.Smo.Server') "$inst,$port" 861 | 862 | # Create the result array 863 | $result = @() 864 | 865 | # Get all the databases 866 | $databases = $server.Databases 867 | 868 | # Loop through the databases 869 | foreach($database in $databases) 870 | { 871 | # Get the database users 872 | $databaseUsers = $database.Users 873 | 874 | # Get the result 875 | $result += $databaseUsers | Select ` 876 | Parent,Name,AsymmetricKey,AuthenticationType,Certificate,` 877 | CreateDate,DateLastModified,DefaultLanguageLcid,DefaultLanguageName,` 878 | DefaultSchema,HasDBAccess,ID,IsSystemObject,Login,LoginType,` 879 | PolicyHealthState,Sid,UserType 880 | } 881 | 882 | # Return the results 883 | return $result 884 | } 885 | catch [Exception] 886 | { 887 | $errorMessage = $_.Exception.Message 888 | $line = $_.InvocationInfo.ScriptLineNumber 889 | $script_name = $_.InvocationInfo.ScriptName 890 | Write-Host "Error: Occurred on line $line in script $script_name." -ForegroundColor Red 891 | Write-Host "Error: $ErrorMessage" -ForegroundColor Red 892 | } 893 | 894 | } 895 | 896 | function Get-SQLDiskLatencies 897 | { 898 | <# 899 | .SYNOPSIS 900 | Get the latencies SQL Server registered on disk 901 | .DESCRIPTION 902 | The script will execute a query against the instance and retrieve 903 | the read and write latencies which SQL Server collected. 904 | .PARAMETER instance 905 | This is the instance that needs to be connected 906 | .PARAMETER port 907 | This is the port of the instance that needs to be used 908 | .EXAMPLE 909 | Get-SQLDiskLatencies "SQL01" 910 | .EXAMPLE 911 | Get-SQLDiskLatencies "SQL01\INST01" 912 | .EXAMPLE 913 | Get-SQLDiskLatencies "SQL01\INST01" 4321 914 | .EXAMPLE 915 | Get-SQLDiskLatencies -inst "SQL01\INST01" 916 | .EXAMPLE 917 | Get-SQLDiskLatencies -inst "SQL01\INST01" port 4321 918 | .INPUTS 919 | .OUTPUTS 920 | System.Array 921 | .NOTES 922 | .LINK 923 | #> 924 | [Cmdletbinding()] 925 | param 926 | ( 927 | [Parameter(Mandatory = $true, Position=1)] 928 | [ValidateNotNullOrEmpty()] 929 | [string]$inst = $null, 930 | [Parameter(Mandatory = $false, Position=2)] 931 | [string]$port = '1433' 932 | ) 933 | 934 | $query = ' 935 | SELECT 936 | DB_NAME(vfs.database_id) AS [Database], 937 | LEFT (mf.physical_name, 2) AS [Drive], 938 | mf.physical_name AS [PhysicalFileName], 939 | --virtual file latency 940 | CASE WHEN num_of_reads = 0 941 | THEN 0 ELSE (io_stall_read_ms / num_of_reads) END AS [ReadLatency], 942 | CASE WHEN num_of_writes = 0 943 | THEN 0 ELSE (io_stall_write_ms / num_of_writes) END AS [WriteLatency], 944 | CASE WHEN (num_of_reads = 0 AND num_of_writes = 0) 945 | THEN 0 ELSE (io_stall / (num_of_reads + num_of_writes)) END AS [Latency], 946 | --avg bytes per IOP 947 | CASE WHEN num_of_reads = 0 948 | THEN 0 ELSE (num_of_bytes_read / num_of_reads) END AS [AvgBPerRead], 949 | CASE WHEN io_stall_write_ms = 0 950 | THEN 0 ELSE (num_of_bytes_written / num_of_writes) END AS [AvgBPerWrite], 951 | CASE WHEN (num_of_reads = 0 AND num_of_writes = 0) 952 | THEN 0 ELSE ((num_of_bytes_read + num_of_bytes_written) / 953 | (num_of_reads + num_of_writes)) END AS [AvgBPerTransfer], 954 | num_of_reads AS [CountReads], 955 | num_of_writes AS [CountWrites], 956 | (num_of_reads+num_of_writes) AS [CountTotalIO], 957 | CONVERT(NUMERIC(10,2),(CAST(num_of_reads AS FLOAT)/ CAST((num_of_reads+num_of_writes) AS FLOAT) * 100)) AS [PercentageRead], 958 | CONVERT(NUMERIC(10,2),(CAST(num_of_writes AS FLOAT)/ CAST((num_of_reads+num_of_writes) AS FLOAT) * 100)) AS [PercentageWrite] 959 | FROM sys.dm_io_virtual_file_stats (NULL,NULL) AS vfs 960 | JOIN sys.master_files AS mf 961 | ON vfs.database_id = mf.database_id 962 | AND vfs.file_id = mf.file_id 963 | ORDER BY DB_NAME(vfs.database_id); 964 | GO 965 | ' 966 | 967 | try{ 968 | $result = Invoke-Sqlcmd -ServerInstance $inst -Query $query 969 | } 970 | catch [Exception] 971 | { 972 | $errorMessage = $_.Exception.Message 973 | $line = $_.InvocationInfo.ScriptLineNumber 974 | $script_name = $_.InvocationInfo.ScriptName 975 | Write-Host "Error: Occurred on line $line in script $script_name." -ForegroundColor Red 976 | Write-Host "Error: $ErrorMessage" -ForegroundColor Red 977 | } 978 | 979 | 980 | return $result 981 | } 982 | 983 | function Get-SQLInstanceSettings 984 | { 985 | <# 986 | .SYNOPSIS 987 | Get the SQL Server instance settings 988 | .DESCRIPTION 989 | This function gets the settings of the instance and return 990 | the data in the form of a table. 991 | .PARAMETER instance 992 | This is the instance that needs to be connected 993 | .PARAMETER port 994 | This is the port of the instance that needs to be used 995 | .EXAMPLE 996 | Get-SQLInstance "SQL01" 997 | .EXAMPLE 998 | Get-SQLInstance "SQL01\INST01" 999 | .EXAMPLE 1000 | Get-SQLInstance "SQL01\INST01" 4321 1001 | .EXAMPLE 1002 | Get-SQLInstance -inst "SQL01\INST01" 1003 | .EXAMPLE 1004 | Get-SQLInstance -inst "SQL01\INST01" -port 4321 1005 | .INPUTS 1006 | .OUTPUTS 1007 | System.Array 1008 | .NOTES 1009 | .LINK 1010 | #> 1011 | [Cmdletbinding()] 1012 | param 1013 | ( 1014 | [Parameter(Mandatory = $true, Position=1)] 1015 | [ValidateNotNullOrEmpty()] 1016 | [string]$inst = $null, 1017 | [Parameter(Mandatory = $false, Position=2)] 1018 | [string]$port = '1433' 1019 | ) 1020 | 1021 | # Check if assembly is loaded 1022 | Load-Assembly -name 'Microsoft.SqlServer.SMO' 1023 | 1024 | # Create the server object and retrieve the information 1025 | try{ 1026 | $server = New-Object ('Microsoft.SqlServer.Management.Smo.Server') "$inst,$port" 1027 | 1028 | # Define the array 1029 | $result = @() 1030 | 1031 | # Get the instance settings 1032 | $result = $server | Select ` 1033 | AuditLevel,BackupDirectory,BrowserServiceAccount,BrowserStartMode,BuildClrVersionString,` 1034 | BuildNumber,ClusterName,ClusterQuorumState,ClusterQuorumType,Collation,CollationID,` 1035 | ComparisonStyle,ComputerNamePhysicalNetBIOS,DefaultFile,DefaultLog,Edition,ErrorLogPath,` 1036 | FilestreamLevel,FilestreamShareName,HadrManagerStatus,InstallDataDirectory,InstallSharedDirectory,` 1037 | InstanceName,IsCaseSensitive,IsClustered,IsFullTextInstalled,IsHadrEnabled,IsSingleUser,IsXTPSupported,` 1038 | Language,LoginMode,MailProfile,MasterDBLogPath,MasterDBPath,MaxPrecision,NamedPipesEnabled,NetName,` 1039 | NumberOfLogFiles,OSVersion,PerfMonMode,PhysicalMemory,PhysicalMemoryUsageInKB,Platform,Processors,` 1040 | ProcessorUsage,Product,ProductLevel,ResourceLastUpdateDateTime,ResourceVersionString,RootDirectory,` 1041 | ServerType,ServiceAccount,ServiceInstanceId,ServiceName,ServiceStartMode,SqlCharSet,SqlCharSetName,` 1042 | SqlDomainGroup,SqlSortOrder,SqlSortOrderName,Status,TapeLoadWaitTime,TcpEnabled,VersionMajor,VersionMinor,` 1043 | VersionString,Name,Version,EngineEdition,ResourceVersion,BuildClrVersion,DefaultTextMode 1044 | 1045 | # Return the result 1046 | return $result 1047 | } 1048 | catch [Exception] 1049 | { 1050 | $errorMessage = $_.Exception.Message 1051 | $line = $_.InvocationInfo.ScriptLineNumber 1052 | $script_name = $_.InvocationInfo.ScriptName 1053 | Write-Host "Error: Occurred on line $line in script $script_name." -ForegroundColor Red 1054 | Write-Host "Error: $ErrorMessage" -ForegroundColor Red 1055 | } 1056 | } 1057 | 1058 | function Get-SQLInstanceUptime 1059 | { 1060 | <# 1061 | .SYNOPSIS 1062 | Get the uptime of the SQL Server instance 1063 | .DESCRIPTION 1064 | The script will execute a query against the instance and retrieve 1065 | the start time. Based on the start time the uptime will be calculated. 1066 | This function can be used from SQL Server 2008 or later 1067 | .PARAMETER instance 1068 | This is the instance that needs to be connected 1069 | .PARAMETER port 1070 | This is the port of the instance that needs to be used 1071 | .EXAMPLE 1072 | Get-SQLInstanceUptime "SQL01" 1073 | .EXAMPLE 1074 | Get-SQLInstanceUptime "SQL01\INST01" 1075 | .EXAMPLE 1076 | Get-SQLInstanceUptime "SQL01\INST01" 4321 1077 | .EXAMPLE 1078 | Get-SQLInstanceUptime -inst "SQL01\INST01" 1079 | .EXAMPLE 1080 | Get-SQLInstanceUptime -inst "SQL01\INST01" -port 4321 1081 | .INPUTS 1082 | .OUTPUTS 1083 | System.Array 1084 | .NOTES 1085 | .LINK 1086 | #> 1087 | [Cmdletbinding()] 1088 | param 1089 | ( 1090 | [Parameter(Mandatory = $true, Position=1)] 1091 | [ValidateNotNullOrEmpty()] 1092 | [string]$inst = $null, 1093 | [Parameter(Mandatory = $false, Position=2)] 1094 | [string]$port = '1433' 1095 | ) 1096 | 1097 | $query = " 1098 | DECLARE @start_time DATETIME , 1099 | @end_time DATETIME , 1100 | @difference DATETIME; 1101 | 1102 | SELECT @start_time = sqlserver_start_time , 1103 | @end_time = GETDATE() , 1104 | @difference = @end_time - @start_time 1105 | FROM sys.dm_os_sys_info; 1106 | 1107 | SELECT @start_time AS [start_time] , 1108 | CONVERT(VARCHAR(10), DATEPART(DAY, @difference) - 1) + ' Day(s) ' 1109 | + RIGHT(CONVERT(VARCHAR(10), 100 + DATEPART(HOUR, @difference)), 2) 1110 | + ':' + RIGHT(CONVERT(VARCHAR(10), 100 + DATEPART(MINUTE, @difference)), 1111 | 2) + ':' + RIGHT(CONVERT(VARCHAR(10), 100 1112 | + DATEPART(SECOND, @difference)), 2) AS [uptime] 1113 | " 1114 | 1115 | try{ 1116 | $result = Invoke-Sqlcmd -ServerInstance $inst -Query $query 1117 | } 1118 | catch [Exception] 1119 | { 1120 | $errorMessage = $_.Exception.Message 1121 | $line = $_.InvocationInfo.ScriptLineNumber 1122 | $script_name = $_.InvocationInfo.ScriptName 1123 | Write-Host "Error: Occurred on line $line in script $script_name." -ForegroundColor Red 1124 | Write-Host "Error: $ErrorMessage" -ForegroundColor Red 1125 | } 1126 | 1127 | return $result 1128 | } 1129 | 1130 | function Get-SQLServerBackups 1131 | { 1132 | <# 1133 | .SYNOPSIS 1134 | Get the database backups 1135 | .DESCRIPTION 1136 | The function will return a list of backups over the last x days. 1137 | The default amount of days is 7 days. 1138 | 1139 | It's possible to enter multiple databases in the database filter parameter. 1140 | Just seperate the databases with a comma (,) 1141 | 1142 | It's possible to enter multiple backup types in the backup type filter parameter. 1143 | Just seperate the backup types with a comma (,) 1144 | Possible backup types are: 1145 | - D: Full back (database backup) 1146 | - I: Incremental 1147 | - L: Log backup 1148 | .PARAMETER instance 1149 | This is the instance that needs to be connected 1150 | .PARAMETER port 1151 | This is the port of the instance that needs to be used 1152 | .EXAMPLE 1153 | Get-SQLServerBackups "SQL01" 1154 | .EXAMPLE 1155 | Get-SQLServerBackups "SQL01\INST01" 1156 | .EXAMPLE 1157 | Get-SQLServerBackups "SQL01\INST01" 4321 1158 | .EXAMPLE 1159 | Get-SQLServerBackups -inst "SQL01\INST01" 1160 | .EXAMPLE 1161 | Get-SQLServerBackups -inst "SQL01\INST01" -port 4321 1162 | .INPUTS 1163 | .OUTPUTS 1164 | System.Array 1165 | .NOTES 1166 | .LINK 1167 | #> 1168 | [Cmdletbinding()] 1169 | param 1170 | ( 1171 | [Parameter(Mandatory = $true, Position=1)] 1172 | [ValidateNotNullOrEmpty()] 1173 | [string]$inst = $null, 1174 | [Parameter(Mandatory = $false, Position=2)] 1175 | [string]$port = '1433' 1176 | , [Parameter(Mandatory = $false, Position=3)] 1177 | [int]$days = 7 1178 | , [Parameter(Mandatory = $false, Position=4)] 1179 | [string]$databaseFilter = $null 1180 | , [Parameter(Mandatory = $false, Position=5)] 1181 | [string]$backupTypeFilter = $null 1182 | 1183 | ) 1184 | 1185 | # Setup the query 1186 | $query = " 1187 | SELECT 1188 | '$inst' AS [server_name], 1189 | bs.database_name AS [database_name], 1190 | bs.backup_start_date AS [start_date], 1191 | bs.backup_finish_date AS [finish_date], 1192 | DATEDIFF(mi, bs.backup_start_date, bs.backup_finish_date) AS [duration], 1193 | bs.expiration_date [experation_date], 1194 | CASE bs.type 1195 | WHEN 'D' THEN 'Full' 1196 | WHEN 'I' THEN 'Differential' 1197 | WHEN 'L' THEN 'Log' 1198 | END AS [backup_type], 1199 | CAST((bs.backup_size / 1024/ 1024) AS INT) AS [size_mb], 1200 | bmf.logical_device_name AS [logical_device_name], 1201 | bmf.physical_device_name AS [physical_device_name], 1202 | bs.name AS [backup_set], 1203 | bs.description AS [description] 1204 | FROM 1205 | msdb.dbo.backupmediafamily bmf 1206 | INNER JOIN msdb.dbo.backupset bs 1207 | ON bmf.media_set_id = bs.media_set_id 1208 | WHERE 1209 | bs.backup_start_date >= DATEADD(d, -$days, GETDATE()) 1210 | " 1211 | 1212 | if($databaseFilter.Length -ge 1) 1213 | { 1214 | if($databaseFilter.Contains(",")) 1215 | { 1216 | $databaseFilter = $databaseFilter.Replace(" ", "") 1217 | $databaseFilter = $databaseFilter.Replace(",", "','") 1218 | $databaseFilter = $databaseFilter.Insert(0, "'").Insert(($databaseFilter.Length + 1), "'") 1219 | 1220 | $query += "AND bs.database_name IN ($databaseFilter) " 1221 | } 1222 | else 1223 | { 1224 | $query += "AND bs.database_name = '$databaseFilter' " 1225 | } 1226 | } 1227 | 1228 | if($backupTypeFilter.Length -ge 1) 1229 | { 1230 | if($backupTypeFilter.Contains(",")) 1231 | { 1232 | $backupTypeFilter = $backupTypeFilter.Replace(" ", "").ToUpper() 1233 | $backupTypeFilter = $backupTypeFilter.Replace(",", "','") 1234 | $backupTypeFilter = $backupTypeFilter.Insert(0, "'").Insert(($backupTypeFilter.Length + 1), "'") 1235 | 1236 | $query += "AND bs.type IN ($backupTypeFilter) " 1237 | } 1238 | else 1239 | { 1240 | $backupTypeFilter = $backupTypeFilter.ToUpper() 1241 | $query += "AND bs.type = '$backupTypeFilter' " 1242 | } 1243 | } 1244 | 1245 | try{ 1246 | $result = Invoke-Sqlcmd -ServerInstance $inst -Query $query 1247 | } 1248 | catch [Exception] 1249 | { 1250 | $errorMessage = $_.Exception.Message 1251 | $line = $_.InvocationInfo.ScriptLineNumber 1252 | $script_name = $_.InvocationInfo.ScriptName 1253 | Write-Host "Error: Occurred on line $line in script $script_name." -ForegroundColor Red 1254 | Write-Host "Error: $ErrorMessage" -ForegroundColor Red 1255 | } 1256 | 1257 | return $result 1258 | } 1259 | 1260 | function Get-SQLServerPrivileges 1261 | { 1262 | <# 1263 | .SYNOPSIS 1264 | Returns each server login with their server roles 1265 | .DESCRIPTION 1266 | This function will return all the logins on the database server 1267 | and check whether they are member of a server role. 1268 | .PARAMETER instance 1269 | This is the instance that needs to be connected 1270 | .PARAMETER port 1271 | This is the port of the instance that needs to be used 1272 | .EXAMPLE 1273 | Get-SQLServerPrivileges "SQL01" 1274 | .EXAMPLE 1275 | Get-SQLServerPrivileges "SQL01\INST01" 1276 | .EXAMPLE 1277 | Get-SQLServerPrivileges "SQL01\INST01" 4321 1278 | .EXAMPLE 1279 | Get-SQLServerPrivileges -inst "SQL01\INST01" 1280 | .EXAMPLE 1281 | Get-SQLServerPrivileges -inst "SQL01\INST01" -port 4321 1282 | .INPUTS 1283 | .OUTPUTS 1284 | System.Array 1285 | .NOTES 1286 | .LINK 1287 | #> 1288 | [Cmdletbinding()] 1289 | param 1290 | ( 1291 | [Parameter(Mandatory = $true, Position=1)] 1292 | [ValidateNotNullOrEmpty()] 1293 | [string]$inst = $null, 1294 | [Parameter(Mandatory = $false, Position=2)] 1295 | [string]$port = '1433' 1296 | ) 1297 | 1298 | # Check if assembly is loaded 1299 | Load-Assembly -name 'Microsoft.SqlServer.SMO' 1300 | 1301 | # Create the server object and retrieve the information 1302 | try{ 1303 | $server = New-Object ('Microsoft.SqlServer.Management.Smo.Server') "$inst,$port" 1304 | 1305 | # Create the result array 1306 | $result = @() 1307 | 1308 | # Create the array for the server roles 1309 | $serverRoles = @() 1310 | 1311 | # Get all the logins 1312 | $logins = $server.Logins 1313 | 1314 | # Loop through the logins 1315 | foreach($login in $logins) 1316 | { 1317 | 1318 | if(($login.Name -notlike "##*")) 1319 | { 1320 | # Get all the server 1321 | $serverRoles = ($login.ListMembers()) -join "," 1322 | 1323 | # Make the result 1324 | if($serverRoles.Count -gt 1) 1325 | { 1326 | $result += $login | Select ` 1327 | Name,LoginType,CreateDate,DateLastModified,IsDisabled,` 1328 | @{N="ServerRoles";E=([string]::Join(",", $serverRoles))} | Sort-Object Name 1329 | } 1330 | else 1331 | { 1332 | $result += $login | Select ` 1333 | Name,LoginType,CreateDate,DateLastModified,IsDisabled,` 1334 | @{N="ServerRoles";E={$serverRoles}} | Sort-Object Name 1335 | } 1336 | 1337 | # Clear the array 1338 | $serverRoles = @() 1339 | } 1340 | } 1341 | 1342 | return $result 1343 | } 1344 | catch [Exception] 1345 | { 1346 | $errorMessage = $_.Exception.Message 1347 | $line = $_.InvocationInfo.ScriptLineNumber 1348 | $script_name = $_.InvocationInfo.ScriptName 1349 | Write-Host "Error: Occurred on line $line in script $script_name." -ForegroundColor Red 1350 | Write-Host "Error: $ErrorMessage" -ForegroundColor Red 1351 | } 1352 | } 1353 | 1354 | 1355 | function Export-DatabaseObject 1356 | { 1357 | <# 1358 | .SYNOPSIS 1359 | Generates export files of database objects 1360 | .DESCRIPTION 1361 | This function will return generate an export file of database objects to a .sql file. 1362 | This includes tables, views, stored procedures and user defined functions. 1363 | .PARAMETER instance 1364 | This is the instance that needs to be connected 1365 | .PARAMETER port 1366 | This is the port of the instance that needs to be used 1367 | .PARAMETER path 1368 | Path to export to 1369 | .PARAMETER dblist 1370 | List with databases to export. Is comma seperated. 1371 | .PARAMETER includetimestamp 1372 | Boolean to include a timestamp directory to export to 1373 | .PARAMETER includetables 1374 | Boolean to include or exclude tables. Can be value $false/$true or 0/1. 1375 | .PARAMETER includeviews 1376 | Boolean to include or exclude views. Can be value $false/$true or 0/1. 1377 | .PARAMETER includesp 1378 | Boolean to include or exclude stored procedures. Can be value $false/$true or 0/1. 1379 | .PARAMETER includeudf 1380 | Boolean to include or exclude user defined functions. Can be value $false/$true or 0/1. 1381 | .EXAMPLE 1382 | Export-DatabaseObject "SQL01" -path 'C:\Temp\export' 1383 | .EXAMPLE 1384 | Export-DatabaseObject -inst "SQL01\INST01" -path 'C:\Temp\export' 1385 | .EXAMPLE 1386 | Export-DatabaseObject -inst "SQL01\INST01" 4321 -path 'C:\Temp\export' 1387 | .EXAMPLE 1388 | Export-DatabaseObject -inst "SQL01\INST01" -dblist 'db1,db2' -path 'C:\Temp\export' 1389 | .EXAMPLE 1390 | Export-DatabaseObject -inst "SQL01\INST01" -includeudf $false -path 'C:\Temp\export' 1391 | .INPUTS 1392 | .OUTPUTS 1393 | Script files 1394 | .NOTES 1395 | .LINK 1396 | #> 1397 | param 1398 | ( 1399 | [Parameter(Mandatory = $true, Position=1)] 1400 | [ValidateNotNullOrEmpty()][string]$inst = $null, 1401 | [Parameter(Mandatory = $false, Position=2)] 1402 | [string]$port = '1433', 1403 | [Parameter(Mandatory = $true, Position=3)] 1404 | [ValidateNotNullOrEmpty()][string]$path = $null, 1405 | [Parameter(Mandatory = $false, Position=4)] 1406 | [string]$dblist = 'ALL', 1407 | [Parameter(Mandatory = $false, Position=5)] 1408 | [Alias("timestamp")] 1409 | [bool]$includetimestamp = $true, 1410 | [Parameter(Mandatory = $false, Position=6)] 1411 | [Alias("inct")] 1412 | [bool]$includetables = $true, 1413 | [Parameter(Mandatory = $false, Position=7)] 1414 | [Alias("incv")] 1415 | [bool]$includeviews = $true, 1416 | [Parameter(Mandatory = $false, Position=8)] 1417 | [Alias("incsp")] 1418 | [bool]$includesp = $true, 1419 | [Parameter(Mandatory = $false, Position=9)] 1420 | [Alias("incu")] 1421 | [bool]$includeudf = $true 1422 | 1423 | ) 1424 | 1425 | # Check if assembly is loaded 1426 | Load-Assembly -name 'Microsoft.SqlServer.SMO' 1427 | 1428 | # Create the server object and retrieve the information 1429 | try{ 1430 | # Make a connection to the database 1431 | $server = New-Object ('Microsoft.SqlServer.Management.Smo.Server') "$inst,$port" 1432 | 1433 | # Set the destination 1434 | $destination = "$path\$inst\" 1435 | 1436 | if((Test-Path $destination) -eq $false) 1437 | { 1438 | # Create the directory 1439 | New-Item -ItemType Directory -Path "$destination" | Out-Null 1440 | } 1441 | 1442 | $databases = @{} 1443 | 1444 | # Check if a selective list must be used 1445 | if($dblist -eq 'ALL') 1446 | { 1447 | # Get the user databases, the system databases are excluded 1448 | $databases = $server.Databases | Select Name | where {$_.Name -notmatch 'master|model|msdb|tempdb' } 1449 | } 1450 | else 1451 | { 1452 | $databases = @() 1453 | 1454 | #clean up the data 1455 | $dblist = $dblist.Replace(' ', '') 1456 | 1457 | # Split the string 1458 | $values = $dblist.Split(',') 1459 | 1460 | foreach($value in $values) 1461 | { 1462 | $db = New-Object psobject 1463 | $db | Add-Member -membertype noteproperty -name "Name" -Value $value 1464 | $databases += $db 1465 | } 1466 | 1467 | } 1468 | 1469 | # Check if there are any databases 1470 | if($databases.Count -ge 1) 1471 | { 1472 | # Loop through 1473 | foreach($database in $databases) 1474 | { 1475 | Write-Host "Starting Database Export: " $database.Name -ForegroundColor Green 1476 | 1477 | # Check if timestamp is needed 1478 | if($includetimestamp) 1479 | { 1480 | # Create a timestamp 1481 | $timestamp = Get-Date -Format yyyyMMddHHmmss 1482 | # Set the desitnation 1483 | $dbDestination = "$destination\" + $database.Name + "\$timestamp" 1484 | } 1485 | else 1486 | { 1487 | # Set the desitnation 1488 | $dbDestination = "$destination\" + $database.Name 1489 | } 1490 | 1491 | # Create the variable for holding all the database objects 1492 | $objects = $null 1493 | 1494 | # Check if the tables need to be included 1495 | if($includetables) 1496 | { 1497 | Write-Host "Retrieving Tables" -ForegroundColor Green 1498 | 1499 | # Get the tables 1500 | $objects += $server.Databases[$database.Name].Tables | where {!($_.IsSystemObject)} 1501 | } 1502 | 1503 | # Check if the views need to be included 1504 | if($includeviews) 1505 | { 1506 | Write-Host "Retrieving Views" -ForegroundColor Green 1507 | 1508 | # Get the views 1509 | $objects += $server.Databases[$database.Name].Views | where {!($_.IsSystemObject)} 1510 | } 1511 | 1512 | # Check if the stored procedures need to be included 1513 | if($includesp) 1514 | { 1515 | Write-Host "Retrieving Stored Procedures" -ForegroundColor Green 1516 | 1517 | # Get the stored procedures 1518 | $objects += $server.Databases[$database.Name].StoredProcedures | where {!($_.IsSystemObject)} 1519 | } 1520 | 1521 | # Check if the user defined functions need to be included 1522 | if($includeudf) 1523 | { 1524 | Write-Host "Retrieving User Defined Functions" -ForegroundColor Green 1525 | 1526 | # Get the stored procedures 1527 | $objects += $server.Databases[$database.Name].UserDefinedFunctions | where {!($_.IsSystemObject)} 1528 | } 1529 | 1530 | Write-Host $objects.Length "objects found to export." -ForegroundColor Green 1531 | 1532 | # Check if there any objects to export 1533 | if($objects.Length -ge 1) 1534 | { 1535 | # Create the scripter object 1536 | $scripter = New-Object ("Microsoft.SqlServer.Management.Smo.Scripter") $server #"$inst,$port" 1537 | 1538 | # Set general options 1539 | $scripter.Options.AppendToFile = $false 1540 | $scripter.Options.AllowSystemObjects = $false 1541 | $scripter.Options.ClusteredIndexes = $true 1542 | $scripter.Options.DriAll = $true 1543 | $scripter.Options.ScriptDrops = $false 1544 | $scripter.Options.IncludeHeaders = $true 1545 | $scripter.Options.ToFileOnly = $true 1546 | $scripter.Options.Indexes = $true 1547 | $scripter.Options.WithDependencies = $false 1548 | 1549 | foreach($item in $objects ) 1550 | { 1551 | # Get the type of object 1552 | $typeDir = $item.GetType().Name 1553 | 1554 | # Check if the directory for the item type exists 1555 | if((Test-Path "$dbDestination\$typeDir") -eq $false) 1556 | { 1557 | New-Item -ItemType Directory -Name "$typeDir" -Path "$dbDestination" | Out-Null 1558 | } 1559 | 1560 | #Setup the output file for the item 1561 | $filename = $item -replace "\[|\]" 1562 | $scripter.Options.FileName = "$dbDestination\$typeDir\$filename.sql" 1563 | 1564 | # Script out the object 1565 | Write-Host "Scripting out $typeDir $item" 1566 | $scripter.Script($item) 1567 | 1568 | } 1569 | } 1570 | } 1571 | } 1572 | else 1573 | { 1574 | Write-Host "No databases found." -ForegroundColor Magenta 1575 | } 1576 | } 1577 | catch [Exception] 1578 | { 1579 | $errorMessage = $_.Exception.Message 1580 | $line = $_.InvocationInfo.ScriptLineNumber 1581 | $script_name = $_.InvocationInfo.ScriptName 1582 | Write-Host "Error: Occurred on line $line in script $script_name." -ForegroundColor Red 1583 | Write-Host "Error: $ErrorMessage" -ForegroundColor Red 1584 | } 1585 | } 1586 | 1587 | 1588 | function Export-SQLServerObject 1589 | { 1590 | <# 1591 | .SYNOPSIS 1592 | Generates export files of SQL Server objects 1593 | .DESCRIPTION 1594 | This function will return generate an export file of SQL Server objects to a .sql file. 1595 | This includes server roles, logins, linked servers, triggers, database mail and jobs. 1596 | .PARAMETER instance 1597 | This is the instance that needs to be connected 1598 | .PARAMETER port 1599 | This is the port of the instance that needs to be used 1600 | .PARAMETER path 1601 | Path to export to 1602 | .PARAMETER includetimestamp 1603 | Boolean to include a timestamp directory to export to 1604 | .PARAMETER includeroles 1605 | Boolean to include or exclude server roles. Can be value $false/$true or 0/1. 1606 | .PARAMETER includelogins 1607 | Boolean to include or exclude logins. Can be value $false/$true or 0/1. 1608 | .PARAMETER includelinkedservers 1609 | Boolean to include or exclude linked servers. Can be value $false/$true or 0/1. 1610 | .PARAMETER includetriggers 1611 | Boolean to include or exclude triggers. Can be value $false/$true or 0/1. 1612 | .PARAMETER includemail 1613 | Boolean to include or exclude database mail. Can be value $false/$true or 0/1. 1614 | .PARAMETER includejobs 1615 | Boolean to include or exclude jobs. Can be value $false/$true or 0/1. 1616 | .EXAMPLE 1617 | Export-SQLServerObject "SQL01" -path 'C:\Temp\export' 1618 | .EXAMPLE 1619 | Export-SQLServerObject -inst "SQL01\INST01" -path 'C:\Temp\export' 1620 | .EXAMPLE 1621 | Export-SQLServerObject -inst "SQL01\INST01" 4321 -path 'C:\Temp\export' 1622 | .EXAMPLE 1623 | Export-SQLServerObject -inst "SQL01\INST01" -includemail $false -path 'C:\Temp\export' 1624 | .INPUTS 1625 | .OUTPUTS 1626 | Script files 1627 | .NOTES 1628 | .LINK 1629 | #> 1630 | param 1631 | ( 1632 | [Parameter(Mandatory = $true, Position=1)] 1633 | [ValidateNotNullOrEmpty()][string]$inst = $null, 1634 | [Parameter(Mandatory = $false, Position=2)] 1635 | [string]$port = '1433', 1636 | [Parameter(Mandatory = $true, Position=3)] 1637 | [ValidateNotNullOrEmpty()][string]$path = $null, 1638 | [Parameter(Mandatory = $false, Position=4)] 1639 | [Alias("timestamp")] 1640 | [bool]$includetimestamp = $true, 1641 | [Parameter(Mandatory = $false, Position=5)] 1642 | [Alias("incr")] 1643 | [bool]$includeroles = $true, 1644 | [Parameter(Mandatory = $false, Position=6)] 1645 | [Alias("incl")] 1646 | [bool]$includelogins = $true, 1647 | [Parameter(Mandatory = $false, Position=7)] 1648 | [Alias("incls")] 1649 | [bool]$includelinkedservers = $true, 1650 | [Parameter(Mandatory = $false, Position=8)] 1651 | [Alias("inct")] 1652 | [bool]$includetriggers = $true, 1653 | [Parameter(Mandatory = $false, Position=9)] 1654 | [Alias("incm")] 1655 | [bool]$includemail = $true, 1656 | [Parameter(Mandatory = $false, Position=10)] 1657 | [Alias("incj")] 1658 | [bool]$includejobs = $true 1659 | 1660 | ) 1661 | 1662 | #Load the assembly 1663 | [System.Reflection.Assembly]::LoadWithPartialName('Microsoft.SqlServer.SMO') | out-null 1664 | 1665 | # Create the server object and retrieve the information 1666 | try{ 1667 | # Check if assembly is loaded 1668 | Load-Assembly -name 'Microsoft.SqlServer.SMO' 1669 | 1670 | Write-Host "Starting SQL Server Export: " $inst -ForegroundColor Green 1671 | 1672 | # Set the destination 1673 | $destination = "$path\$inst\" 1674 | 1675 | # Check if timestamp is needed 1676 | if($includetimestamp) 1677 | { 1678 | # Create a timestamp 1679 | $timestamp = Get-Date -Format yyyyMMddHHmmss 1680 | # Set the desitnation 1681 | $destination = "$destination\$timestamp" 1682 | } 1683 | 1684 | if((Test-Path $destination) -eq $false) 1685 | { 1686 | # Create the directory 1687 | New-Item -ItemType Directory -Path "$destination" | Out-Null 1688 | } 1689 | 1690 | # Create the variable for holding all the server objects 1691 | [array]$objects = $null 1692 | 1693 | # Get the roles 1694 | if($includeroles -eq $true) 1695 | { 1696 | Write-Host "Retrieving Server Roles" -ForegroundColor Green 1697 | $objects += $server.Roles | where {($_.IsFixedRole -eq $false) -and ($_.Name -ne 'public')} 1698 | } 1699 | 1700 | # Get the logins 1701 | if($includelogins -eq $true) 1702 | { 1703 | Write-Host "Retrieving Logins" -ForegroundColor Green 1704 | $objects += $server.Logins | where {$_.Name -notmatch 'BUILTIN*|NT SERVICE*|NT AUTHORITY*|##*|sa'} 1705 | } 1706 | 1707 | 1708 | # Get the linked servers 1709 | if($includelinkedservers -eq $true) 1710 | { 1711 | Write-Host "Retrieving Linked Servers" -ForegroundColor Green 1712 | $objects += $server.LinkedServers 1713 | } 1714 | 1715 | # Get the triggers 1716 | if($includetriggers -eq $true) 1717 | { 1718 | Write-Host "Retrieving Triggers" -ForegroundColor Green 1719 | $objects += $server.Triggers 1720 | } 1721 | 1722 | # Get the mail objects 1723 | if($includemail -eq $true) 1724 | { 1725 | Write-Host "Retrieving Database Mail" -ForegroundColor Green 1726 | $objects += $server.Mail 1727 | $objects += $server.Mail.Accounts 1728 | $objects += $server.Mail.Profiles 1729 | } 1730 | 1731 | # Get the job objects 1732 | if($includejobs -eq $true) 1733 | { 1734 | Write-Host "Retrieving Jobs" -ForegroundColor Green 1735 | $objects += $server.JobServer.Operators 1736 | $objects += $server.JobServer.Jobs 1737 | $objects += $server.JobServer.Alerts 1738 | } 1739 | 1740 | Write-Host $objects.Length "objects found to export." -ForegroundColor Green 1741 | 1742 | # Check if there any objects to export 1743 | if($objects.Length -ge 1) 1744 | { 1745 | # Create the scripter object 1746 | $scripter = New-Object ("Microsoft.SqlServer.Management.Smo.Scripter") $server #"$inst,$port" 1747 | 1748 | # Set general options 1749 | $scripter.Options.AppendToFile = $false 1750 | $scripter.Options.AllowSystemObjects = $false 1751 | $scripter.Options.ClusteredIndexes = $true 1752 | $scripter.Options.DriAll = $true 1753 | $scripter.Options.ScriptDrops = $false 1754 | $scripter.Options.IncludeHeaders = $true 1755 | $scripter.Options.ToFileOnly = $true 1756 | $scripter.Options.Indexes = $true 1757 | $scripter.Options.WithDependencies = $false 1758 | 1759 | foreach($item in $objects ) 1760 | { 1761 | # Get the type of object 1762 | $typeDir = $item.GetType().Name 1763 | 1764 | # Check if the directory for the item type exists 1765 | if((Test-Path "$destination\$typeDir") -eq $false) 1766 | { 1767 | New-Item -ItemType Directory -Name "$typeDir" -path "$destination" | Out-Null 1768 | } 1769 | 1770 | #Setup the output file for the item 1771 | $filename = $item -replace "\[|\]" 1772 | 1773 | # Check if the filename contains a "\", if so replace it 1774 | if($filename -match "\\") 1775 | { 1776 | $filename = $filename -replace "\\", "_" 1777 | } 1778 | 1779 | $scripter.Options.FileName = "$destination\$typeDir\$filename.sql" 1780 | 1781 | # Script out the object 1782 | Write-Host "Scripting out $typeDir $item" 1783 | 1784 | $scripter.Script($item) 1785 | } 1786 | } 1787 | } 1788 | catch [Exception] 1789 | { 1790 | $errorMessage = $_.Exception.Message 1791 | $line = $_.InvocationInfo.ScriptLineNumber 1792 | $script_name = $_.InvocationInfo.ScriptName 1793 | Write-Host "Error: Occurred on line $line in script $script_name." -ForegroundColor Red 1794 | Write-Host "Error: $ErrorMessage" -ForegroundColor Red 1795 | } 1796 | } 1797 | 1798 | ################################################## 1799 | 1800 | function Load-Assembly 1801 | { 1802 | <# 1803 | .SYNOPSIS 1804 | Check if a assembly is loaded and load it if neccesary 1805 | .DESCRIPTION 1806 | The script will check if an assembly is already loaded. 1807 | If it isn't already loaded it will try to load the assembly 1808 | .PARAMETER name 1809 | Full name of the assembly to be loaded 1810 | .EXAMPLE 1811 | Load-Assembly -name 'Microsoft.SqlServer.SMO' 1812 | .INPUTS 1813 | .OUTPUTS 1814 | .NOTES 1815 | .LINK 1816 | #> 1817 | param( 1818 | [Parameter(Mandatory = $true)][ValidateNotNullOrEmpty()] 1819 | [String] $name 1820 | ) 1821 | 1822 | if(([System.AppDomain]::Currentdomain.GetAssemblies() | where {$_ -match $name}) -eq $null) 1823 | { 1824 | try{ 1825 | [System.Reflection.Assembly]::LoadWithPartialName($name) | Out-Null 1826 | } 1827 | catch [System.Exception] 1828 | { 1829 | Write-Host "Failed to load assembly!" -ForegroundColor Red 1830 | Write-Host "$_.Exception.GetType().FullName, $_.Exception.Message" -ForegroundColor Red 1831 | } 1832 | } 1833 | } 1834 | 1835 | Export-ModuleMember -Function Get-HostHarddisk 1836 | Export-ModuleMember -Function Get-HostHardware 1837 | Export-ModuleMember -Function Get-HostOperatingSystem 1838 | Export-ModuleMember -Function Get-HostSQLServerServices 1839 | Export-ModuleMember -Function Get-HostSystemInformation 1840 | Export-ModuleMember -Function Get-HostUptime 1841 | 1842 | Export-ModuleMember -Function Get-SQLAgentJobs 1843 | Export-ModuleMember -Function Get-SQLConfiguration 1844 | Export-ModuleMember -Function Get-SQLDatabaseFiles 1845 | Export-ModuleMember -Function Get-SQLDatabasePrivileges 1846 | Export-ModuleMember -Function Get-SQLDatabases 1847 | Export-ModuleMember -Function Get-SQLDatabaseUsers 1848 | Export-ModuleMember -Function Get-SQLDiskLatencies 1849 | Export-ModuleMember -Function Get-SQLInstanceSettings 1850 | Export-ModuleMember -Function Get-SQLInstanceUptime 1851 | Export-ModuleMember -Function Get-SQLServerBackups 1852 | Export-ModuleMember -Function Get-SQLServerPrivileges 1853 | 1854 | Export-ModuleMember -Function Export-DatabaseObject 1855 | Export-ModuleMember -Function Export-SQLServerObject 1856 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # PSSQLLib 2 | Powershell SQL Server Library 3 | 4 | ## Features 5 | 6 | The library has the following features: 7 | 8 | * Export database objects 9 | * Export SQL Server objects 10 | * Get the host harddisk information 11 | * Get the host hardware 12 | * Get the host operating system information 13 | * Get the host uptime 14 | * Get the SQL Server instance settings 15 | * Get the SQL Server instance configuration settings 16 | * Get the SQL Server instance uptime 17 | * Get the SQL Server login server privileges 18 | * Get the SQL Server databases 19 | * Get the SQL Server database files 20 | * Get the SQL Server database users 21 | * Get the SQL Server database user privileges 22 | * Get the SQL Server Agent jobs 23 | * Get the SQL Server disk latencies 24 | 25 | ## Installation 26 | Unzip the file. 27 | 28 | Make a directory (if not already present) named "PSSQLLib" in one of the following standard Powershell Module directories: 29 | * $Home\Documents\WindowsPowerShell\Modules (%UserProfile%\Documents\WindowsPowerShell\Modules) 30 | * $Env:ProgramFiles\WindowsPowerShell\Modules (%ProgramFiles%\ WindowsPowerShell\Modules) 31 | * $Systemroot\System32\WindowsPowerShell\v1.0\Modules (%systemroot%\System32\ WindowsPowerShell\v1.0\Modules) 32 | 33 | Place both the psd1 and psm1 files in the module directory created earlier. 34 | 35 | Execute the following command in a PowerShell command screen: 36 | Import-Module PSSQLLib 37 | 38 | To check if the module is imported correctly execute the following command: 39 | Get-Command -Module PSSQLLib 40 | or 41 | Get-Module -Name PSSQLLib 42 | 43 | You should be able to see a list of functions 44 | --------------------------------------------------------------------------------