Для подключения к базе данных MS SQL с помощью SQL Server Database Engine в powershell нужно создать экземпляр Server класса пространства имён Microsoft.SqlServer.Management.Smo .NET Framework.
В начале нужно подключить сборку
[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SqlServer.Smo");
Затем создаём экземпляр класса
$svr = new-object Microsoft.SqlServer.Management.Smo.ServerУ него очень много свойств:
AuditLevel :
BackupDirectory :
BrowserServiceAccount :
BrowserStartMode :
BuildClrVersionString :
BuildNumber :
ClusterName :
ClusterQuorumState :
ClusterQuorumType :
Collation :
CollationID :
ComparisonStyle :
ComputerNamePhysicalNetBIOS :
DefaultFile :
DefaultLog :
Edition :
ErrorLogPath :
FilestreamLevel :
FilestreamShareName :
HadrManagerStatus :
InstallDataDirectory :
InstallSharedDirectory :
InstanceName :
IsCaseSensitive :
IsClustered :
IsFullTextInstalled :
IsHadrEnabled :
IsSingleUser :
IsXTPSupported :
Language :
LoginMode :
MailProfile :
MasterDBLogPath :
MasterDBPath :
MaxPrecision :
NamedPipesEnabled :
NetName :
NumberOfLogFiles :
OSVersion :
PerfMonMode :
PhysicalMemory :
PhysicalMemoryUsageInKB :
Platform :
Processors :
ProcessorUsage :
Product :
ProductLevel :
ResourceLastUpdateDateTime :
ResourceVersionString :
RootDirectory :
ServerType :
ServiceAccount :
ServiceInstanceId :
ServiceName :
ServiceStartMode :
SqlCharSet :
SqlCharSetName :
SqlDomainGroup :
SqlSortOrder :
SqlSortOrderName :
Status :
TapeLoadWaitTime :
TcpEnabled :
VersionMajor :
VersionMinor :
VersionString :
Name : PRV-LAPTOP
Version :
EngineEdition :
ResourceVersion :
BuildClrVersion :
DefaultTextMode : True
Configuration : Microsoft.SqlServer.Management.Smo.Configuration
AffinityInfo :
ProxyAccount :
Mail :
Databases :
Endpoints :
Languages :
SystemMessages :
UserDefinedMessages :
Credentials :
CryptographicProviders :
Logins :
Roles :
LinkedServers :
SystemDataTypes :
JobServer :
ResourceGovernor :
ServiceMasterKey :
SmartAdmin :
Settings : Microsoft.SqlServer.Management.Smo.Settings
Information : Microsoft.SqlServer.Management.Smo.Information
UserOptions : Microsoft.SqlServer.Management.Smo.UserOptions
BackupDevices :
FullTextService :
ActiveDirectory :
Triggers :
Audits :
ServerAuditSpecifications :
AvailabilityGroups :
ConnectionContext : Data Source=.;Integrated Security=True;MultipleActiveResultSets=False;Application Name="У
правление SQL"
Events : Microsoft.SqlServer.Management.Smo.ServerEvents
OleDbProviderSettings :
Urn :
Properties :
UserData :
State : Existing
IsDesignMode : False
DomainName : SMO
DomainInstanceName :
Для начала достаточно задать только следующее
$svr.connectioncontext.connectionstring="server=srv-sql\begemot;uid=sa;pwd=SECRET;database=logos"С таким результатом для объекта $svr.connectioncontext:
StatementTimeout : 600
ConnectionType : DatabaseEngine
BatchSeparator : GO
TransactionDepth : 0
SqlExecutionModes : ExecuteSql
FixedServerRoles : SysAdmin, ServerAdmin, SetupAdmin, SecurityAdmin, ProcessAdmin, DBCreator, DiskAdmin, BulkAdmin
UserProfile : All
ProcessID : 51
TrueLogin : sa
TrueName : SRV-SQL\BEGEMOT
InUse : True
LockTimeout : -1
ServerVersion : 12.0.4100
DatabaseEngineType : Standalone
SqlConnectionObject : System.Data.SqlClient.SqlConnection
IsOpen : True
CapturedSql : Microsoft.SqlServer.Management.Common.CapturedSql
AutoDisconnectMode : DisconnectIfPooled
IsForceDisconnected : False
ServerInstance : .
Login :
Password :
SecurePassword : System.Security.SecureString
LoginSecure : True
ConnectAsUserName :
ConnectAsUserPassword :
ConnectAsUser : False
NonPooledConnection : False
PooledConnectionLifetime : 0
MinPoolSize : 0
MaxPoolSize : 100
ConnectTimeout : 15
ConnectionString : server=srv-sql\begemot;uid=sa;pwd=SECRET;database=logos
SecureConnectionString : System.Security.SecureString
NetworkProtocol : NotSpecified
ApplicationName : Управление SQL
WorkstationId :
DatabaseName :
PacketSize : 8192
MultipleActiveResultSets : False
EncryptConnection : False
Теперь открываем соединение
$svr.connectioncontext.connect()И у $svr становятся следующие свойства:
AuditLevel : FailureЛистинг тут.
BackupDirectory : C:\Program Files\Microsoft SQL Server\MSSQL12.BEGEMOT\MSSQL\Backup
BrowserServiceAccount : NT AUTHORITY\LOCALSERVICE
BrowserStartMode : Auto
BuildClrVersionString : v4.0.30319
BuildNumber : 4100
ClusterName :
ClusterQuorumState : NotApplicable
ClusterQuorumType : NotApplicable
Collation : Cyrillic_General_CI_AS
CollationID : 53269
ComparisonStyle : 196609
ComputerNamePhysicalNetBIOS : SRV-SQL
DefaultFile : C:\Program Files\Microsoft SQL Server\MSSQL12.BEGEMOT\MSSQL\DATA\
DefaultLog : C:\Program Files\Microsoft SQL Server\MSSQL12.BEGEMOT\MSSQL\DATA\
Edition : Enterprise Edition (64-bit)
ErrorLogPath : C:\Program Files\Microsoft SQL Server\MSSQL12.BEGEMOT\MSSQL\Log
FilestreamLevel : Disabled
FilestreamShareName : BEGEMOT
HadrManagerStatus : Failed
InstallDataDirectory : C:\Program Files\Microsoft SQL Server\MSSQL12.BEGEMOT\MSSQL
InstallSharedDirectory : C:\Program Files\Microsoft SQL Server\MSSQL12.BEGEMOT\MSSQL
InstanceName : BEGEMOT
IsCaseSensitive : False
IsClustered : False
IsFullTextInstalled : True
IsHadrEnabled : False
IsSingleUser : False
IsXTPSupported : True
Language : Русский (Россия)
LoginMode : Mixed
MailProfile :
MasterDBLogPath : C:\Program Files\Microsoft SQL Server\MSSQL12.BEGEMOT\MSSQL\DATA
MasterDBPath : C:\Program Files\Microsoft SQL Server\MSSQL12.BEGEMOT\MSSQL\DATA
MaxPrecision : 38
NamedPipesEnabled : False
NetName : SRV-SQL
NumberOfLogFiles : -1
OSVersion : 6.3 (9600)
PerfMonMode : None
PhysicalMemory : 2021
PhysicalMemoryUsageInKB : 256132
Platform : NT x64
Processors : 1
ProcessorUsage :
Product : Microsoft SQL Server
ProductLevel : SP1
ResourceLastUpdateDateTime : 20.04.2015 18:48:56
ResourceVersionString : 12.00.4100
RootDirectory : C:\Program Files\Microsoft SQL Server\MSSQL12.BEGEMOT\MSSQL
ServerType : Standalone
ServiceAccount : NT Service\MSSQL$BEGEMOT
ServiceInstanceId : MSSQL12.BEGEMOT
ServiceName : BEGEMOT
ServiceStartMode : Auto
SqlCharSet : 5
SqlCharSetName : cp1251
SqlDomainGroup : NT Service\MSSQL$BEGEMOT
SqlSortOrder : 0
SqlSortOrderName : bin_ascii_8
Status : Online
TapeLoadWaitTime : -1
TcpEnabled : True
VersionMajor : 12
VersionMinor : 0
VersionString : 12.0.4100.1
Name : PRV-LAPTOP
Version : 12.0.4100
EngineEdition : EnterpriseOrDeveloper
ResourceVersion : 12.0.4100
BuildClrVersion : 4.0.30319
DefaultTextMode : True
Configuration : Microsoft.SqlServer.Management.Smo.Configuration
AffinityInfo : Microsoft.SqlServer.Management.Smo.AffinityInfo
ProxyAccount : [PRV-LAPTOP]
Mail : [PRV-LAPTOP]
Databases : {LOGOS, master, model, msdb...}
Endpoints : {Dedicated Admin Connection, TSQL Default TCP, TSQL Default VIA, TSQL Local Machine...}
Languages : {Arabic, British, čeština, Dansk...}
SystemMessages : {21, 21, 21, 21...}
UserDefinedMessages : {}
Credentials : {}
CryptographicProviders : {}
Logins : {##MS_PolicyEventProcessingLogin##, ##MS_PolicyTsqlExecutionLogin##, NT AUTHORITY\СИСТЕМА
, NT Service\MSSQL$BEGEMOT...}
Roles : {bulkadmin, dbcreator, diskadmin, processadmin...}
LinkedServers : {}
SystemDataTypes : {bigint, binary, bit, char...}
JobServer : [PRV-LAPTOP]
ResourceGovernor : Microsoft.SqlServer.Management.Smo.ResourceGovernor
ServiceMasterKey : Microsoft.SqlServer.Management.Smo.ServiceMasterKey
SmartAdmin : Microsoft.SqlServer.Management.Smo.SmartAdmin
Settings : Microsoft.SqlServer.Management.Smo.Settings
Information : Microsoft.SqlServer.Management.Smo.Information
UserOptions : Microsoft.SqlServer.Management.Smo.UserOptions
BackupDevices : {}
FullTextService : [PRV-LAPTOP]
ActiveDirectory :
Triggers : {}
Audits : {}
ServerAuditSpecifications : {}
AvailabilityGroups : {}
ConnectionContext : server=srv-sql\begemot;uid=sa;pwd=SECRET;database=logos
Events : Microsoft.SqlServer.Management.Smo.ServerEvents
OleDbProviderSettings :
Urn : Server[@Name='SRV-SQL\BEGEMOT']
Properties : {Name=AuditLevel/Type=Microsoft.SqlServer.Management.Smo.AuditLevel/Writable=True/Value=F ailure, Name=BackupDirectory/Type=System.String/Writable=True/Value=C:\Program Files\Microsoft SQL Server\MSSQL12.BEGEMOT\MSSQL\Backup, Name=BuildNumber/Type=System.Int32/Writabl
e=False/Value=4100, Name=DefaultFile/Type=System.String/Writable=True/Value=C:\Program Fi
les\Microsoft SQL Server\MSSQL12.BEGEMOT\MSSQL\DATA\...}
UserData :
State : Existing
IsDesignMode : False
DomainName : SMO
DomainInstanceName : SRV-SQL\BEGEMOT
Комментариев нет :
Отправить комментарий