Skip to content

Commit

Permalink
Import-SqlDscPreferredModule: Add new command (dsccommunity#1846)
Browse files Browse the repository at this point in the history
- SqlServerDsc
  - The following public functions were added to the module (see comment-based
    help for more information):
    - `Import-SqlDscPreferredModule`
  - The module will now call `Import-SqlDscPreferredModule` when the module
    is imported to make sure SqlServer (default preferred module) or SQLPS
    is loaded into the session. This will make it possible for classes and
    commands to use and return SQL types. If no module is found it will
    output a warning to install any of the dependent modules.
- SqlServerDsc.Common
  - `Import-SQLPSModule`
    - The function was changed to call public command `Import-SqlDscPreferredModule`.
  • Loading branch information
johlju authored Feb 5, 2023
1 parent 3a46100 commit 49cf40c
Show file tree
Hide file tree
Showing 81 changed files with 798 additions and 455 deletions.
12 changes: 12 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
- `Get-LocalizedDataRecursive`
- Added documentation how to generate stub modules for the unit tests.
The documentation can be found in ['tests/Unit/Stubs`](https://github.com/dsccommunity/SqlServerDsc/tree/main/tests/Unit/Stubs).
- SqlRSSetup and SqlRS
- Removed the integration test when running against SQL Server 2019,
due to the URL to download the Reporting Services 2019 executable
no longer works.

### Added

Expand All @@ -55,6 +59,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
- `Complete-SqlDscImage`
- `Complete-SqlDscFailoverCluster`
- `Initialize-SqlDscRebuildDatabase`
- `Import-SqlDscPreferredModule`
- New GitHub issue templates for proposing new public commands, proposing
an enhancement to an existing command, or having a problem with an existing
command.
Expand Down Expand Up @@ -121,6 +126,11 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
in AppVeyor to help maximize the time alloted be run.
- The stubs in `SqlServerStub.psm1` are now based on the commands from the
module SqlServer v22.0.49-preview.
- The module will now call `Import-SqlDscPreferredModule` when the module
is imported to make sure SqlServer (default preferred module) or SQLPS
is loaded into the session. This will make it possible for classes and
commands to use and return SQL types. If no module is found it will
output a warning to install any of the dependent modules.
- `Install-SqlServerDsc`
- No longer throws an exception when parameter `AgtSvcAccount` is not specified.
- SqlAgReplica
Expand Down Expand Up @@ -177,6 +187,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
when passed to the command ([issue #1837](https://github.com/dsccommunity/SqlServerDsc/issues/1837)).
- Now returns a more clear error message when the status of a database
instance is not `Online`.
- `Import-SQLPSModule`
- The function was changed to call public command `Import-SqlDscPreferredModule`.
- SqlTraceFlag
- The examples was updated to show that values should be passed as an array,
even when there is only one value.
Expand Down
8 changes: 8 additions & 0 deletions azure-pipelines.yml
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,9 @@ stages:
pool:
vmImage: 'windows-2022'
timeoutInMinutes: 0
variables:
# This sets environment variable $env:SqlServerDscCI.
SqlServerDscCI: true
steps:
- task: DownloadPipelineArtifact@2
displayName: 'Download Build Artifact'
Expand Down Expand Up @@ -105,6 +108,9 @@ stages:
pool:
vmImage: 'windows-2019'
timeoutInMinutes: 0
variables:
# This sets environment variable $env:SqlServerDscCI.
SqlServerDscCI: true
steps:
- task: DownloadPipelineArtifact@2
displayName: 'Download Build Artifact'
Expand Down Expand Up @@ -168,6 +174,8 @@ stages:
variables:
# This sets environment variable $env:CI.
CI: true
# This sets environment variable $env:SqlServerDscCI.
SqlServerDscCI: true
steps:
- task: DownloadPipelineArtifact@2
displayName: 'Download Build Artifact'
Expand Down
1 change: 1 addition & 0 deletions build.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@ CopyPaths:
- en-US
- Modules
Prefix: prefix.ps1
Suffix: suffix.ps1
Encoding: UTF8
VersionedOutputDirectory: true
BuiltModuleSubdirectory: builtModule
Expand Down
2 changes: 0 additions & 2 deletions source/Modules/SqlServerDsc.Common/SqlServerDsc.Common.psd1
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,6 @@
'Get-ProtocolNameProperties'
'Get-ServerProtocolObject'
'Import-Assembly'
'Set-PSModulePath'
'ConvertTo-ServerInstanceName'
'Get-FilePathMajorVersion'
'Test-FeatureFlag'
Expand All @@ -75,4 +74,3 @@

} # End of PrivateData hashtable
}

107 changes: 1 addition & 106 deletions source/Modules/SqlServerDsc.Common/SqlServerDsc.Common.psm1
Original file line number Diff line number Diff line change
Expand Up @@ -880,112 +880,7 @@ function Import-SQLPSModule
$Force
)

if ($Force.IsPresent)
{
Write-Verbose -Message $script:localizedData.ModuleForceRemoval -Verbose
Remove-Module -Name @('SqlServer', 'SQLPS', 'SQLASCmdlets') -Force -ErrorAction SilentlyContinue
}

<#
Check if either of the modules are already loaded into the session.
Prefer to use the first one (in order found).
NOTE: There should actually only be either SqlServer or SQLPS loaded,
otherwise there can be problems with wrong assemblies being loaded.
#>
$loadedModuleName = (Get-Module -Name @('SqlServer', 'SQLPS') | Select-Object -First 1).Name
if ($loadedModuleName)
{
Write-Verbose -Message ($script:localizedData.PowerShellModuleAlreadyImported -f $loadedModuleName) -Verbose
return
}

$availableModuleName = $null

# Get the newest SqlServer module if more than one exist
$availableModule = Get-Module -FullyQualifiedName 'SqlServer' -ListAvailable |
Sort-Object -Property 'Version' -Descending |
Select-Object -First 1 -Property Name, Path, Version

if ($availableModule)
{
$availableModuleName = $availableModule.Name

Write-Verbose -Message ($script:localizedData.PreferredModuleFound -f $availableModuleName) -Verbose
}
else
{
Write-Verbose -Message ($script:localizedData.PreferredModuleNotFound) -Verbose

<#
After installing SQL Server the current PowerShell session doesn't know about the new path
that was added for the SQLPS module.
This reloads PowerShell session environment variable PSModulePath to make sure it contains
all paths.
#>
Set-PSModulePath -Path ([System.Environment]::GetEnvironmentVariable('PSModulePath', 'Machine'))

<#
Get the newest SQLPS module if more than one exist.
#>
$availableModule = Get-Module -FullyQualifiedName 'SQLPS' -ListAvailable |
Select-Object -Property Name, Path, @{
Name = 'Version'
Expression = {
# Parse the build version number '120', '130' from the Path.
(Select-String -InputObject $_.Path -Pattern '\\([0-9]{3})\\' -List).Matches.Groups[1].Value
}
} |
Sort-Object -Property 'Version' -Descending |
Select-Object -First 1

if ($availableModule)
{
# This sets $availableModuleName to the Path of the module to be loaded.
$availableModuleName = Split-Path -Path $availableModule.Path -Parent
}
}

if ($availableModuleName)
{
try
{
Write-Debug -Message ($script:localizedData.DebugMessagePushingLocation)
Push-Location

<#
SQLPS has unapproved verbs, disable checking to ignore Warnings.
Suppressing verbose so all cmdlet is not listed.
#>
$importedModule = Import-Module -Name $availableModuleName -DisableNameChecking -Verbose:$false -Force:$Force -PassThru -ErrorAction Stop

<#
SQLPS returns two entries, one with module type 'Script' and another with module type 'Manifest'.
Only return the object with module type 'Manifest'.
SqlServer only returns one object (of module type 'Script'), so no need to do anything for SqlServer module.
#>
if ($availableModuleName -ne 'SqlServer')
{
$importedModule = $importedModule | Where-Object -Property 'ModuleType' -EQ -Value 'Manifest'
}

Write-Verbose -Message ($script:localizedData.ImportedPowerShellModule -f $importedModule.Name, $importedModule.Version, $importedModule.Path) -Verbose
}
catch
{
$errorMessage = $script:localizedData.FailedToImportPowerShellSqlModule -f $availableModuleName
New-InvalidOperationException -Message $errorMessage -ErrorRecord $_
}
finally
{
Write-Debug -Message ($script:localizedData.DebugMessagePoppingLocation)
Pop-Location
}
}
else
{
$errorMessage = $script:localizedData.PowerShellSqlModuleNotFound
New-InvalidOperationException -Message $errorMessage
}
Import-SqlDscPreferredModule @PSBoundParameters
}

<#
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,15 +16,6 @@ ConvertFrom-StringData @'
ConnectedToAnalysisServicesInstance = Connected to Analysis Services instance '{0}'. (SQLCOMMON0020)
FailedToConnectToAnalysisServicesInstance = Failed to connect to Analysis Services instance '{0}'. (SQLCOMMON0021)
SqlServerVersionIsInvalid = Could not get the SQL version for the instance '{0}'. (SQLCOMMON0022)
PreferredModuleFound = Preferred module {0} found. (SQLCOMMON0023)
PreferredModuleNotFound = Information: No preferred PowerShell module was found, trying to use the SQLPS module. (SQLCOMMON0024)
ImportedPowerShellModule = Importing PowerShell module '{0}' with version '{1}' from path '{2}'. (SQLCOMMON0025)
PowerShellModuleAlreadyImported = Found PowerShell module {0} already imported in the session. (SQLCOMMON0026)
ModuleForceRemoval = Forcibly removed the SQL PowerShell module from the session to import it fresh again. (SQLCOMMON0027)
DebugMessagePushingLocation = SQLPS module changes CWD to SQLSERVER:\ when loading, pushing location to pop it when module is loaded. (SQLCOMMON0028)
DebugMessagePoppingLocation = Popping location back to what it was before importing SQLPS module. (SQLCOMMON0029)
PowerShellSqlModuleNotFound = Neither PowerShell module SqlServer or SQLPS was found. Unable to run SQL Server cmdlets. (SQLCOMMON0030)
FailedToImportPowerShellSqlModule = Failed to import {0} module. (SQLCOMMON0031)
GetSqlServerClusterResources = Getting cluster resource for SQL Server. (SQLCOMMON0032)
GetSqlAgentClusterResource = Getting active cluster resource SQL Server Agent. (SQLCOMMON0033)
BringClusterResourcesOffline = Bringing the SQL Server resources '{0}' offline. (SQLCOMMON0034)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,15 +22,6 @@ ConvertFrom-StringData @'
ConnectedToAnalysisServicesInstance = Ansluten till Analysis Services instans '{0}'. (SQLCOMMON0020)
FailedToConnectToAnalysisServicesInstance = Misslyckades att ansluta till Analysis Services instans '{0}'. (SQLCOMMON0021)
SqlServerVersionIsInvalid = Kunde inte hämta SQL version för instansen '{0}'. (SQLCOMMON0022)
PreferredModuleFound = Föredragen modul SqlServer funnen. (SQLCOMMON0023)
PreferredModuleNotFound = Information: PowerShell modul SqlServer ej funnen, försöker att använda äldre SQLPS modul. (SQLCOMMON0024)
ImportedPowerShellModule = Importerade PowerShell modul '{0}' med version '{1}' från mapp '{2}'. (SQLCOMMON0025)
PowerShellModuleAlreadyImported = Fann att PowerShell modul {0} redan är importerad i sessionen. (SQLCOMMON0026)
ModuleForceRemoval = Tvingade bort den tidigare SQL PowerShell modulen från sessionen för att importera den fräsch igen. (SQLCOMMON0027)
DebugMessagePushingLocation = SQLPS modul ändrar nuvarande katalog till SQLSERVER:\ när modulen laddas, sparar nuvarande katalog så den kan återställas efter modulen laddats. (SQLCOMMON0028)
DebugMessagePoppingLocation = Återställer nuvarande katalog till vad den var innan modulen SQLPS importerades. (SQLCOMMON0029)
PowerShellSqlModuleNotFound = Varken PowerShell modulen SqlServer eller SQLPS kunde hittas. Kommer inte kunna köra SQL Server cmdlets. (SQLCOMMON0030)
FailedToImportPowerShellSqlModule = Misslyckades att importera {0} modulen. (SQLCOMMON0031)
GetSqlServerClusterResources = Hämtar kluster resurser för SQL Server. (SQLCOMMON0032)
GetSqlAgentClusterResource = Hämtar aktiva kluster resurser för SQL Server Agent. (SQLCOMMON0033)
BringClusterResourcesOffline = Tar SQL Server resurser '{0}' offline. (SQLCOMMON0034)
Expand Down
Loading

0 comments on commit 49cf40c

Please sign in to comment.