Verwalten von SQL Server für Linux mit PowerShell CoreManage SQL Server on Linux with PowerShell Core
In diesem Artikel werden SQL Server PowerShell und einige Beispiele zur Verwendung mit PowerShell Core (PS Core) unter macOS und Linux vorgestellt.This article introduces SQL Server PowerShell and walks you through a couple of examples on how to use it with PowerShell Core (PS Core) on macOS & Linux. PowerShell Core ist jetzt ein Open Source-Projekt auf GitHub.PowerShell Core is now an Open Source project on GitHub.
Plattformübergreifende Editor-OptionenCross-platform editor options
Alle unten genannten Schritte mit PowerShell Core funktionieren in einem regulären Terminal. Alternativ dazu können Sie die Schritte auch in einem Terminal in VS Code oder Azure Data Studio ausführen.All of the steps PowerShell Core below will work in a regular terminal, or you can run them from a terminal within VS Code or Azure Data Studio. Sowohl VS Code als auch Azure Data Studio sind unter macOS und Linux verfügbar.Both VS Code and Azure Data Studio are available on macOS and Linux. Weitere Informationen zu Azure Data Studio finden Sie in dieser Schnellstartanleitung.For more information on Azure Data Studio, see this quickstart. Sie können auch die Verwendung der PowerShell-Erweiterung in Betracht ziehen.You may also want to consider using the PowerShell extension for it.
Installieren von PowerShell CoreInstalling PowerShell Core
Weitere Informationen zur Installation von PowerShell Core auf verschiedenen unterstützten und experimentellen Plattformen finden Sie in den folgenden Artikeln:For more information on installing PowerShell Core on various supported and experimental platforms, see the following articles:
- Installieren von PowerShell Core unter WindowsInstalling PowerShell Core on Windows
- Installieren von PowerShell Core unter LinuxInstalling PowerShell Core on Linux
- Installieren von PowerShell Core unter macOSInstalling PowerShell Core on macOS
- Installieren von PowerShell Core unter ARMInstalling PowerShell Core on ARM
Installieren des SqlServer-ModulsInstall the SqlServer module
Das SqlServer
-Modul wird im PowerShell-Katalog verwaltet.The SqlServer
module is maintained in the PowerShell Gallery. Wenn Sie mit SQL Server arbeiten, sollten Sie immer die neueste Version der PowerShell-Moduls „SqlServer“ verwenden.When working with SQL Server, you should always use the most recent version of the SqlServer PowerShell module.
Um das SqlServer-Modul zu installieren, öffnen Sie eine PowerShell Core-Sitzung, und führen Sie den folgenden Code aus:To install the SqlServer module, open a PowerShell Core session and run the following code:
Install-Module -Name SqlServer
Weitere Informationen zum Installieren des SqlServer-Moduls aus dem PowerShell-Katalog finden Sie auf dieser Seite.For more information on how to install the SqlServer module from the PowerShell Gallery, see this page.
Verwenden des SqlServer-ModulsUsing the SqlServer module
Starten Sie zunächst PowerShell Core.Let's start by launching PowerShell Core. Wenn Sie auf einem macOS- oder Linux-Computer arbeiten, öffnen Sie eine Terminalsitzung, und geben Sie pwsh ein, um eine neue PowerShell Core-Sitzung zu starten.If you are on macOS or Linux, Open a terminal session on your computer, and type pwsh to launch a new PowerShell Core session. Unter Windows verwenden Sie Win+R und geben pwsh
ein, um eine neue PowerShell Core-Sitzung zu starten.On Windows, use Win+R, and type pwsh
to launch a new PowerShell Core session.
pwsh
SQL Server stellt ein PowerShell-Modul namens SqlServer bereit.SQL Server provides a PowerShell module named SqlServer. Sie können das Modul SqlServer verwenden, um die SQL Server-Komponenten (SQL Server-Anbieter und -Cmdlets) in eine PowerShell-Umgebung oder ein PowerShell-Skript zu importieren.You can use the SqlServer module to import the SQL Server components (SQL Server provider and cmdlets) into a PowerShell environment or script.
Kopieren Sie den folgenden Befehl in die PowerShell-Eingabeaufforderung, um das Modul SqlServer in Ihre aktuelle PowerShell-Sitzung zu importieren:Copy and paste the following command at the PowerShell prompt to import the SqlServer module into your current PowerShell session:
Import-Module SqlServer
Geben Sie den folgenden Befehl in die PowerShell-Eingabeaufforderung ein, um zu überprüfen, ob das SqlServer-Modul ordnungsgemäß importiert wurde:Type the following command at the PowerShell prompt to verify that the SqlServer module was imported correctly:
Get-Module -Name SqlServer
PowerShell sollte Informationen ähnlich der folgenden Ausgabe anzeigen:PowerShell should display information similar to the following output:
ModuleType Version Name ExportedCommands
---------- ------- ---- ----------------
Script 21.1.18102 SqlServer {Add-SqlAvailabilityDatabase, Add-SqlAvailabilityGroupList...
Herstellen einer Verbindung mit SQL Server und Abrufen von ServerinformationenConnect to SQL Server and get server information
In den folgenden Schritten wird PowerShell Core verwendet, um eine Verbindung mit Ihrer SQL Server-Instanz unter Linux herzustellen und einige Servereigenschaften anzuzeigen.The following steps use PowerShell Core to connect to your SQL Server instance on Linux and display a couple of server properties.
Kopieren Sie die folgenden Befehle in die PowerShell-Eingabeaufforderung.Copy and paste the following commands at the PowerShell prompt. Wenn Sie diese Befehle ausführen, führt PowerShell Folgendes aus:When you run these commands, PowerShell will:
- Ein Dialogfeld wird angezeigt, das Sie auffordert, den Hostnamen oder die IP-Adresse Ihrer Instanz einzugeben.Display a dialog that prompts you for the hostname or IP address of your instance
- Das Dialogfeld Bei PowerShell anmelden wird angezeigt, das Sie auffordert, die Anmeldeinformationen einzugeben.Display the PowerShell credential request dialog, which prompts you for the credentials. Sie können Ihren SQL-Benutzernamen und Ihr SQL-Kennwort verwenden, um eine Verbindung mit Ihrer SQL Server-Instanz unter Linux herzustellen.You can use your SQL username and SQL password to connect to your SQL Server instance on Linux
- Das Cmdlet Get-SqlInstance wird verwendet, um eine Verbindung mit dem Server herzustellen und einige Eigenschaften anzuzeigen.Use the Get-SqlInstance cmdlet to connect to the Server and display a few properties
Optional können Sie einfach die $serverInstance
-Variable durch die IP-Adresse oder den Hostnamen Ihrer SQL Server-Instanz ersetzen.Optionally, you can just replace the $serverInstance
variable with the IP address or the hostname of your SQL Server instance.
# Prompt for instance & credentials to login into SQL Server
$serverInstance = Read-Host "Enter the name of your instance"
$credential = Get-Credential
# Connect to the Server and return a few properties
Get-SqlInstance -ServerInstance $serverInstance -Credential $credential
# done
PowerShell sollte Informationen ähnlich der folgenden Ausgabe anzeigen:PowerShell should display information similar to the following output:
Instance Name Version ProductLevel UpdateLevel HostPlatform HostDistribution
------------- ------- ------------ ----------- ------------ ----------------
your_server_instance 14.0.3048 RTM CU13 Linux Ubuntu
Hinweis
Wenn für diese Werte nichts angezeigt wird, ist beim Herstellen einer Verbindung mit der SQL Server-Zielinstanz höchstwahrscheinlich ein Fehler aufgetreten.If nothing is displayed for these values, the connection to the target SQL Server instance most likely failed. Stellen Sie sicher, dass Sie dieselben Verbindungsinformationen verwenden können, um eine Verbindung über SQL Server Management Studio herzustellen.Make sure that you can use the same connection information to connect from SQL Server Management Studio. Überprüfen Sie anschließend die Empfehlungen zur Verbindungsproblembehandlung.Then review the connection troubleshooting recommendations.
Verwenden des SQL Server PowerShell-AnbietersUsing the SQL Server PowerShell Provider
Die Verwendung des SQL Server PowerShell-Anbieters ist eine weitere Option zum Herstellen einer Verbindung mit Ihrer SQL Server-Instanz.Another option for connecting to your SQL Server instance is to use the SQL Server PowerShell Provider. Dieser Anbieter ermöglicht Ihnen die Navigation Ihrer SQL Server-Instanz über die Befehlszeile, so als würden Sie in der Struktur im Objekt-Explorer navigieren.Using the provider allows you to navigate SQL Server instance similar to as if you were navigating the tree structure in Object Explorer, but at the cmdline. Dieser Anbieter wird standardmäßig als PSDrive (PowerShell-Laufwerk) namens SQLSERVER:\
dargestellt, das Sie verwenden können, um Verbindungen mit SQL Server-Instanzen herzustellen, auf die Ihr Domänenkonto zugreifen kann, und in diesen zu navigieren.By default this provider is presented as a PSDrive named SQLSERVER:\
which you can use to connect & navigate SQL Server instances that your domain account has access to. Informationen zum Einrichten der Active Directory-Authentifizierung für SQL Server für Linux finden Sie in den Konfigurationsschritten.See Configuration steps for information on how to setup Active Directory authentication for SQL Server on Linux.
Für den SQL Server PowerShell-Anbieter können Sie auch die SQL-Authentifizierung verwenden.You can also use SQL authentication with the SQL Server PowerShell Provider. Verwenden Sie hierzu das Cmdlet New-PSDrive
, um ein neues PSDrive zu erstellen, und geben Sie die entsprechenden Anmeldeinformationen zum Herstellen einer Verbindung an.To do this, use the New-PSDrive
cmdlet to create a new PSDrive and supply the proper credentials to connect.
Das folgende Beispiel zeigt, wie Sie unter Verwendung der SQL-Authentifizierung ein neues PSDrive erstellen.In this example below, you will see an example of how to create a new PSDrive using SQL authentication.
# NOTE: We are reusing the values saved in the $credential variable from the above example.
New-PSDrive -Name SQLonDocker -PSProvider SqlServer -Root 'SQLSERVER:\SQL\localhost,10002\Default\' -Credential $credential
Sie können überprüfen, ob das Laufwerk erstellt wurde, indem Sie das Cmdlet Get-PSDrive
ausführen.You can confirm that the drive was created by running the Get-PSDrive
cmdlet.
Get-PSDrive
Sobald Sie das neue PSDrive erstellt haben, können Sie damit beginnen, darin zu navigieren.Once you have created your new PSDrive, you can start navigating it.
dir SQLonDocker:\Databases
Die Ausgabe kann wie folgt aussehen.Here is what the output might look like. Möglicherweise stellen Sie fest, dass die Ausgabe derjenigen ähnelt, die SSMS auf dem Datenbankknoten anzeigt.You might notice this output is similar to what SSMS will display at the Databases node. Es werden die Benutzerdatenbanken angezeigt, aber nicht die Systemdatenbanken.It displays the user databases, but not the system databases.
Name Status Size Space Recovery Compat. Owner
Available Model Level
---- ------ ---- ---------- -------- ------- -----
AdventureWorks2016 Normal 209.63 MB 1.31 MB Simple 130 sa
AdventureWorksDW2012 Normal 167.00 MB 32.47 MB Simple 110 sa
AdventureWorksDW2014 Normal 188.00 MB 78.10 MB Simple 120 sa
AdventureWorksDW2016 Normal 172.00 MB 74.76 MB Simple 130 sa
AdventureWorksDW2017 Normal 208.00 MB 40.57 MB Simple 140 sa
Wenn Sie alle Datenbanken in Ihrer Instanz anzeigen müssen, bietet sich beispielsweise das Cmdlet Get-SqlDatabase
an.If you need to see all databases on your instance, one option is to use the Get-SqlDatabase
cmdlet.
Abrufen von DatenbankenGet Databases
Ein wichtiges Cmdlet, das Sie kennen müssen, ist Get-SqlDatabase
.An important cmdlet to know is the Get-SqlDatabase
. Bei vielen Vorgängen, die eine Datenbank oder Objekte in einer Datenbank einbeziehen, kann das Cmdlet Get-SqlDatabase
verwendet werden.For many operations that involve a database, or objects within a database, the Get-SqlDatabase
cmdlet can be used. Wenn Sie Werte für den -ServerInstance
-Parameter und den -Database
-Parameter angeben, wird nur dieses Datenbankobjekt abgerufen.If you supply values for both the -ServerInstance
and -Database
parameters, only that one database object will be retrieved. Wenn Sie jedoch nur den -ServerInstance
-Parameter angeben, wird eine vollständige Liste aller Datenbanken in dieser Instanz zurückgegeben.However, if you specify only the -ServerInstance
parameter, a full list of all databases on that instance will be returned.
# NOTE: We are reusing the values saved in the $credential variable from the above example.
# Connect to the Instance and retrieve all databases
Get-SqlDatabase -ServerInstance ServerB -Credential $credential
Hier sehen Sie ein Beispiel einer möglichen Rückgabe des oben genannten Get-SqlDatabase-Befehls:Here is a sample of what might be returned by the Get-SqlDatabase command above:
Name Status Size Space Recovery Compat. Owner
Available Model Level
---- ------ ---- ---------- -------- ------- -----
AdventureWorks2016 Normal 209.63 MB 1.31 MB Simple 130 sa
AdventureWorksDW2012 Normal 167.00 MB 32.47 MB Simple 110 sa
AdventureWorksDW2014 Normal 188.00 MB 78.10 MB Simple 120 sa
AdventureWorksDW2016 Normal 172.00 MB 74.88 MB Simple 130 sa
AdventureWorksDW2017 Normal 208.00 MB 40.63 MB Simple 140 sa
master Normal 6.00 MB 600.00 KB Simple 140 sa
model Normal 16.00 MB 5.70 MB Full 140 sa
msdb Normal 15.50 MB 1.14 MB Simple 140 sa
tempdb Normal 16.00 MB 5.49 MB Simple 140 sa
Untersuchen von SQL Server-FehlerprotokollenExamine SQL Server error logs
In den folgenden Schritten wird PowerShell Core zum Untersuchen von Fehlerprotokollen zu Ihrer SQL Server-Instanz unter Linux verwendet.The following steps use PowerShell Core to examine error logs connect on your SQL Server instance on Linux.
Kopieren Sie die folgenden Befehle in die PowerShell-Eingabeaufforderung.Copy and paste the following commands at the PowerShell prompt. Die Ausführung dieser Befehle kann einige Minuten dauern.They might take a few minutes to run. Diese Befehle bewirken Folgendes:These commands do the following steps:
- Ein Dialogfeld wird angezeigt, das Sie auffordert, den Hostnamen oder die IP-Adresse Ihrer Instanz einzugeben.Display a dialog that prompts you for the hostname or IP address of your instance
- Das Dialogfeld Bei PowerShell anmelden wird angezeigt, das Sie auffordert, die Anmeldeinformationen einzugeben.Display the PowerShell credential request dialog that prompts you for the credentials. Sie können Ihren SQL-Benutzernamen und Ihr SQL-Kennwort verwenden, um eine Verbindung mit Ihrer SQL Server-Instanz unter Linux herzustellen.You can use your SQL username and SQL password to connect to your SQL Server instance on Linux
- Das Cmdlet Get-SqlErrorLog wird verwendet, um eine Verbindung mit der SQL Server-Instanz unter Linux herzustellen und die Fehlerprotokolle abzurufen, die seit gestern (Yesterday) aufgetreten sind.Use the Get-SqlErrorLog cmdlet to connect to the SQL Server instance on Linux and retrieve error logs since Yesterday
Alternativ dazu können Sie die $serverInstance
-Variable durch die IP-Adresse oder den Hostnamen Ihrer SQL Server-Instanz ersetzen.Optionally, you can replace the $serverInstance
variable with the IP address or the hostname of your SQL Server instance.
# Prompt for instance & credentials to login into SQL Server
$serverInstance = Read-Host "Enter the name of your instance"
$credential = Get-Credential
# Retrieve error logs since yesterday
Get-SqlErrorLog -ServerInstance $serverInstance -Credential $credential -Since Yesterday
# done
Erkunden der zurzeit in PS Core verfügbaren CmdletsExplore cmdlets currently available in PS Core
Für das SqlServer-Modul stehen derzeit 109 Cmdlets in Windows PowerShell zur Verfügung, davon sind aber nur 62 in PSCore verfügbar.While the SqlServer module currently has 109 cmdlets available in Windows PowerShell, only 62 of the 109 are available in PSCore. Im Folgenden finden Sie eine vollständige Liste der derzeit verfügbaren 59 Cmdlets.A full list of 59 cmdlets currently available is included below. Eine ausführliche Dokumentation aller Cmdlets im SqlServer-Modul finden Sie in der Cmdlet-Referenz zu SqlServer.For in-depth documentation of all cmdlets in the SqlServer module, see the SqlServer cmdlet reference.
Der folgende Befehl zeigt alle Cmdlets an, die in der von Ihnen verwendeten PowerShell-Version verfügbar sind.The following command will show you all of the cmdlets available on the version of PowerShell you are using.
Get-Command -Module SqlServer -CommandType Cmdlet |
SORT -Property Noun |
SELECT Name
- ConvertFrom-EncodedSqlNameConvertFrom-EncodedSqlName
- ConvertTo-EncodedSqlNameConvertTo-EncodedSqlName
- Get-SqlAgentGet-SqlAgent
- Get-SqlAgentJobGet-SqlAgentJob
- Get-SqlAgentJobHistoryGet-SqlAgentJobHistory
- Get-SqlAgentJobScheduleGet-SqlAgentJobSchedule
- Get-SqlAgentJobStepGet-SqlAgentJobStep
- Get-SqlAgentScheduleGet-SqlAgentSchedule
- Invoke-SqlAssessmentInvoke-SqlAssessment
- Get-SqlAssessmentItemGet-SqlAssessmentItem
- Remove-SqlAvailabilityDatabaseRemove-SqlAvailabilityDatabase
- Resume-SqlAvailabilityDatabaseResume-SqlAvailabilityDatabase
- Add-SqlAvailabilityDatabaseAdd-SqlAvailabilityDatabase
- Suspend-SqlAvailabilityDatabaseSuspend-SqlAvailabilityDatabase
- New-SqlAvailabilityGroupNew-SqlAvailabilityGroup
- Set-SqlAvailabilityGroupSet-SqlAvailabilityGroup
- Remove-SqlAvailabilityGroupRemove-SqlAvailabilityGroup
- Switch-SqlAvailabilityGroupSwitch-SqlAvailabilityGroup
- Join-SqlAvailabilityGroupJoin-SqlAvailabilityGroup
- Revoke-SqlAvailabilityGroupCreateAnyDatabaseRevoke-SqlAvailabilityGroupCreateAnyDatabase
- Grant-SqlAvailabilityGroupCreateAnyDatabaseGrant-SqlAvailabilityGroupCreateAnyDatabase
- New-SqlAvailabilityGroupListenerNew-SqlAvailabilityGroupListener
- Set-SqlAvailabilityGroupListenerSet-SqlAvailabilityGroupListener
- Add-SqlAvailabilityGroupListenerStaticIpAdd-SqlAvailabilityGroupListenerStaticIp
- Set-SqlAvailabilityReplicaSet-SqlAvailabilityReplica
- Remove-SqlAvailabilityReplicaRemove-SqlAvailabilityReplica
- New-SqlAvailabilityReplicaNew-SqlAvailabilityReplica
- Set-SqlAvailabilityReplicaRoleToSecondarySet-SqlAvailabilityReplicaRoleToSecondary
- New-SqlBackupEncryptionOptionNew-SqlBackupEncryptionOption
- Get-SqlBackupHistoryGet-SqlBackupHistory
- Invoke-SqlcmdInvoke-Sqlcmd
- New-SqlCngColumnMasterKeySettingsNew-SqlCngColumnMasterKeySettings
- Remove-SqlColumnEncryptionKeyRemove-SqlColumnEncryptionKey
- Get-SqlColumnEncryptionKeyGet-SqlColumnEncryptionKey
- Remove-SqlColumnEncryptionKeyValueRemove-SqlColumnEncryptionKeyValue
- Add-SqlColumnEncryptionKeyValueAdd-SqlColumnEncryptionKeyValue
- Get-SqlColumnMasterKeyGet-SqlColumnMasterKey
- Remove-SqlColumnMasterKeyRemove-SqlColumnMasterKey
- New-SqlColumnMasterKeyNew-SqlColumnMasterKey
- Get-SqlCredentialGet-SqlCredential
- Set-SqlCredentialSet-SqlCredential
- New-SqlCredentialNew-SqlCredential
- Remove-SqlCredentialRemove-SqlCredential
- New-SqlCspColumnMasterKeySettingsNew-SqlCspColumnMasterKeySettings
- Get-SqlDatabaseGet-SqlDatabase
- Restore-SqlDatabaseRestore-SqlDatabase
- Backup_SqlDatabaseBackup-SqlDatabase
- Set-SqlErrorLogSet-SqlErrorLog
- Get-SqlErrorLogGet-SqlErrorLog
- New-SqlHADREndpointNew-SqlHADREndpoint
- Set-SqlHADREndpointSet-SqlHADREndpoint
- Get-SqlInstanceGet-SqlInstance
- Add-SqlLoginAdd-SqlLogin
- Remove-SqlLoginRemove-SqlLogin
- Get-SqlLoginGet-SqlLogin
- Set-SqlSmartAdminSet-SqlSmartAdmin
- Get-SqlSmartAdminGet-SqlSmartAdmin
- Read-SqlTableDataRead-SqlTableData
- Write-SqlTableDataWrite-SqlTableData
- Read-SqlViewDataRead-SqlViewData
- Read-SqlXEventRead-SqlXEvent
- Convert-UrnToPathConvert-UrnToPath
Siehe auchSee also
Feedback
Feedback wird geladen...