Windows 10 下PowerShell安裝 SqlServer module的步驟及問題解決

微軟於今年發佈了SQL Server 2017 on Linux的版本,在Linux上安裝好了SQL Server 2017,微軟的官方提供了以下幾種方式遠程鏈接到數據庫實例:
SQL Server Management Studio (SSMS)
Windows PowerShell
SQL Server Data Tools (SSDT)linux

重點來談一下若是經過PowerShell鏈接(後面簡稱PS)。sql

下載並安裝SSMS

PowerShell 默認是包括在SSMS中的,因此咱們仍然要下載SSMS並安裝它(注意選擇語種平臺,不然下來後安裝會提示語種不兼容,致使安裝失敗)。shell

導入SQL Server module到PS

按照微軟的官方說法,從SSMS的17.0版本開始,SQL Server PowerShell module 再也不包含在SSMS中,而是遷移在了PowerShell Gallery。那麼咱們須要從PS module庫中導入SQL Server module。須要作以下一些事情數據庫

確認NuGet 是否在PackageProvider中

PS C:\windows\system32> Get-PackageProvider -ListAvailable

Name                     Version          DynamicOptions
----                     -------          --------------
msi                      3.0.0.0          AdditionalArguments
msu                      3.0.0.0
PowerShellGet            1.0.0.1          PackageManagementProvider, Type, Scope, AllowClobber, SkipPublisherCheck, ...
Programs                 3.0.0.0          IncludeWindowsInstaller, IncludeSystemComponent

若是不在其中,那麼須要獲取NuGet

PS C:\windows\system32> Install-PackageProvider NuGet -Verbose
VERBOSE: Using the provider 'Bootstrap' for searching packages.
VERBOSE: Finding the package 'Bootstrap::FindPackage' 'NuGet','','','''.
VERBOSE: Performing the operation "Install Package" on target "Package 'nuget' version '2.8.5.208' from
'https://oneget.org/nuget-2.8.5.208.package.swidtag'.".

會提示是否贊成安裝非信任的包,輸入‘yes’windows

The package(s) come(s) from a package source that is not marked as trusted.
Are you sure you want to install software from 'https://oneget.org/nuget-2.8.5.208.package.swidtag'?
[Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help (default is "N"): yes
VERBOSE: Installing the package 'https://oneget.org/nuget-2.8.5.208.package.swidtag'.
VERBOSE: Installed the package 'nuget' to 'C:\Program
Files\PackageManagement\ProviderAssemblies\nuget\2.8.5.208\Microsoft.PackageManagement.NuGetProvider.dll'.

Name                           Version          Source           Summary
----                           -------          ------           -------
nuget                          2.8.5.208        https://onege... NuGet provider for the OneGet meta-package manager

安裝SQL Server module

PS C:\windows\system32> Install-Module -Name SqlServer

Untrusted repository
You are installing the modules from an untrusted repository. If you trust this repository, change its
InstallationPolicy value by running the Set-PSRepository cmdlet. Are you sure you want to install the modules from
'PSGallery'?
[Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help (default is "N"): yes

導入SQL Server module

PS C:\windows\system32> Import-Module SqlServer

若是在導入的過程當中,出現了以下的錯誤,提示UnauthorizedAccesssession

Import-Module : File C:\Program Files\WindowsPowerShell\Modules\SqlServer\21.0.17199\SqlServerPostScript.ps1 cannot be
loaded because running scripts is disabled on this system. For more information, see about_Execution_Policies at
https:/go.microsoft.com/fwlink/?LinkID=135170.
At line:1 char:1
+ Import-Module SqlServer
+ ~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : SecurityError: (:) [Import-Module], PSSecurityException
    + FullyQualifiedErrorId : UnauthorizedAccess,Microsoft.PowerShell.Commands.ImportModuleCommand

執行以下命令,並在提示時輸入yeside

PS C:\windows\system32> Set-ExecutionPolicy RemoteSigned

Execution Policy Change
The execution policy helps protect you from scripts that you do not trust. Changing the execution policy might expose
you to the security risks described in the about_Execution_Policies help topic at
https:/go.microsoft.com/fwlink/?LinkID=135170. 

Do you want to change the execution policy?
[Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help (default is "N"): yes

再次執行導入命令,應該會成功了,能夠查看導入結果測試

PS C:\windows\system32> Import-Module SqlServer
PS C:\windows\system32> Get-Module -Name SqlServer

ModuleType Version    Name                                ExportedCommands
---------- -------    ----                                ----------------
Manifest   21.0.17199 SqlServer                           {Add-RoleMember, Add-SqlAvailabilityDatabase, Add-SqlAvail...

測試導入結果

按照官網的提示,鏈接遠程數據庫實例this

PS C:\windows\system32> $serverInstance = 10.213.22.186
PS C:\windows\system32> $credential = Get-Credential

點擊回車後,會彈出登陸窗口,輸入遠程數據庫的用戶名和密碼,ps會自動保存到session中code

cmdlet Get-Credential at command pipeline position 1
Supply values for the following parameters:
Credential

以後建立數據庫鏈接對象並訪問

# Load the SMO assembly and create a Server object
[System.Reflection.Assembly]::LoadWithPartialName('Microsoft.SqlServer.SMO') | out-null
$server = New-Object ('Microsoft.SqlServer.Management.Smo.Server') $serverInstance

# Set credentials
$server.ConnectionContext.LoginSecure=$false
$server.ConnectionContext.set_Login($credential.UserName)
$server.ConnectionContext.set_SecurePassword($credential.Password)

# Connect to the Server and get a few properties
$server.Information | Select-Object Edition, HostPlatform, HostDistribution | Format-List
# done

會返回選擇的結果信息

Edition          : Express Edition (64-bit)
HostPlatform     : Linux
HostDistribution : Ubuntu

參考鏈接

https://docs.microsoft.com/en...
https://docs.microsoft.com/en...
https://docs.microsoft.com/en...