Load the SqlServer or SQLPS module in PowerShell
Check whether the SQL Server module is loaded in PowerShell, then load it (SqlServer first, SQLPS as fallback).
The SqlServer module is the current PowerShell module for SQL Server; SQLPS is the older module shipped with SQL Server. The script below loads whichever one is available, if neither is already loaded in the session, without changing the current location.
# Test to see if the SQLPS module is loaded, and if not, load it
#if (-not((Get-Module -name 'SQLPS') -or (Get-Module -name 'sqlserver'))) { " to load"} else {"altready"}
if (-not((Get-Module -name 'SQLPS') -or (Get-Module -name 'sqlserver')))
{
If (Get-Module -name SQLServer -ListAvailable)
{
Write-Verbose "Preferred SQLServer module found"
$module = Get-Module SQLServer -ListAvailable
}
else
{
Write-Verbose "SQLServer module not found, using older SQLPS module "
$module = Get-Module SQLPS -ListAvailable
}
Push-Location # The SQLPS module load changes location to the Provider, so save the current location
Import-Module $module -WarningAction SilentlyContinue -ErrorAction Stop
Pop-Location # Now go back to the original location
}
Notes
- The script loads nothing if
SQLPSorsqlserveris already loaded. - The
SQLServermodule is preferred when it is installed; otherwise the script falls back toSQLPS. -ErrorAction Stopmakes the script fail if neither module is installed.