How to get the SQL Server variables via the operating system?
Example:
ERROR LOG = D:\Program Files\Microsoft SQL Server\MSSQL11.SQL2012\MSSQL\Log\ERRORLOG
DB VERSION = 13.0.5026.0
DB HOME = D:\Program Files\Microsoft SQL Server\MSSQL13.SQL2012\MSSQL
INSTANCE NAME = SQL2012
I'm trying to capture the information by Powershell but with no success...
Attempts made:
Windows:
gci env:* | sort-object name
Regedit:
(get-itemproperty 'HKLM:\SOFTWARE\Microsoft\Microsoft SQL Server')
Related
I have to change the service accounts of hundreds of SQL Servers and agents.
Microsoft recommends using the SQL Server configuration manager. This way works fine, but it is horrible if you have to do it hundred times.
On the more recent servers (Windows Server 2016, SQL Server 2016/2017) that PowerShell works fine:
$computer = $env:computername
[void][reflection.assembly]::LoadWithPartialName("Microsoft.SqlServer.Smo")
[void][reflection.assembly]::LoadWithPartialName("Microsoft.SqlServer.SqlWmiManagement")
$wmi = New-Object ("Microsoft.SqlServer.Management.Smo.Wmi.ManagedComputer") $computer
$wmi.Services | Select Name, DisplayName, Type, StartMode, ServiceState,
ServiceAccount | ft -auto
$sqlserver = $wmi.Services | where {$_.Type -eq "SqlServer"}
$sqlserver.SetServiceAccount($account, $pw)
But nearly every older server (Windows Server 2008-2012R2, SQL Server 2008-2014) gives me a empty WmiConnectionInfo an the exception:
ConnectionSettings : Microsoft.SqlServer.Management.Smo.Wmi.WmiConnectionInfo
Services :
ClientProtocols :
ServerInstances :
ServerAliases :
Urn : ManagedComputer[#Name='SERVER']
Name : SERVER
Properties : {}
UserData :
State : Existing
The following exception occurred while trying to enumerate the collection: "SQL Server WMI provider is not available on SERVER.".
On the older server I checked the loaded assembylies. [reflection.assembly]::LoadWithPartialName("Microsoft.SqlServer.Smo").FullName gives [...] Version=13.0.0.0 [...].
SQL Server 2014 is version 12, not 13.
But even if I load the right (?) versions of the dlls, the result stays the same.
[reflection.assembly]::Load("Microsoft.SqlServer.Smo, Version=12.0.0.0, Culture=neutral, PublicKeyToken=...")
[reflection.assembly]::Load("Microsoft.SqlServer.SqlWmiManagement, Version=12.0.0.0, Culture=neutral, PublicKeyToken=...")
Do I have to load more assemblies with the correct version?
Is there another recommended way to change the SQL Server service accounts via PowerShell?
Interesting. There appears to be some incompatibility with the assemblies and Server 2012. If I run this against an SQL Server 2012 instance:
Add-Type -AssemblyName "Microsoft.SqlServer.Smo, Version=12.0.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91"
Add-Type -AssemblyName "Microsoft.SqlServer.SqlWmiManagement, Version=12.0.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91"
$wmi = New-Object -TypeName "Microsoft.SqlServer.Management.Smo.Wmi.ManagedComputer" -ArgumentList $ServerName
$wmi.Services | Select-Object -Property Name, DisplayName, Type, StartMode, ServiceState, ServiceAccount | Format-Table -AutoSize
I get:
Name DisplayName Type StartMode ServiceState
---- ----------- ---- --------- ------------
MsDtsServer100 SQL Server Integration Services 10.0 SqlServerIntegrationService Disabled Stopped
(Note: I've cut off the ServiceAccount column here intentionally for privacy purposes.)
But against an SQL Server 2008 R2 instance, I get:
Name DisplayName Type StartMode ServiceState
---- ----------- ---- --------- ------------
MsDtsServer100 SQL Server Integration Services 10.0 SqlServerIntegrationService Auto Running
MSSQLFDLauncher SQL Full-text Filter Daemon Launcher (MSSQLSERVER) 9 Manual Running
MSSQLSERVER SQL Server (MSSQLSERVER) SqlServer Auto Running
MSSQLServerOLAPService SQL Server Analysis Services (MSSQLSERVER) AnalysisServer Auto Running
ReportServer SQL Server Reporting Services (MSSQLSERVER) ReportServer Auto Running
SQLBrowser SQL Server Browser SqlBrowser Disabled Stopped
SQLSERVERAGENT SQL Server Agent (MSSQLSERVER) SqlAgent Auto Running
However, if I use v14 of the assemblies:
Add-Type -AssemblyName "Microsoft.SqlServer.Smo, Version=14.0.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91"
Add-Type -AssemblyName "Microsoft.SqlServer.SqlWmiManagement, Version=14.0.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91"
$wmi = New-Object -TypeName "Microsoft.SqlServer.Management.Smo.Wmi.ManagedComputer" -ArgumentList $ServerName
$wmi.Services | Select-Object -Property Name, DisplayName, Type, StartMode, ServiceState, ServiceAccount | Format-Table -AutoSize
SQL Server 2012:
Name DisplayName Type StartMode ServiceState
---- ----------- ---- --------- ------------
MsDtsServer100 SQL Server Integration Services 10.0 SqlServerIntegrationService Disabled Stopped
MsDtsServer110 SQL Server Integration Services 11.0 SqlServerIntegrationService Auto Running
MSSQLFDLauncher SQL Full-text Filter Daemon Launcher (MSSQLSERVER) 9 Manual Running
MSSQLSERVER SQL Server (MSSQLSERVER) SqlServer Auto Running
MSSQLServerOLAPService SQL Server Analysis Services (MSSQLSERVER) AnalysisServer Auto Running
ReportServer SQL Server Reporting Services (MSSQLSERVER) ReportServer Auto Running
SQLBrowser SQL Server Browser SqlBrowser Auto Running
SQLSERVERAGENT SQL Server Agent (MSSQLSERVER) SqlAgent Auto Running
SQL Server 2008 R2:
Name DisplayName Type StartMode ServiceState
---- ----------- ---- --------- ------------
MsDtsServer100 SQL Server Integration Services 10.0 SqlServerIntegrationService Auto Running
MSSQLFDLauncher SQL Full-text Filter Daemon Launcher (MSSQLSERVER) 9 Manual Running
MSSQLSERVER SQL Server (MSSQLSERVER) SqlServer Auto Running
MSSQLServerOLAPService SQL Server Analysis Services (MSSQLSERVER) AnalysisServer Auto Running
ReportServer SQL Server Reporting Services (MSSQLSERVER) ReportServer Auto Running
SQLBrowser SQL Server Browser SqlBrowser Disabled Stopped
SQLSERVERAGENT SQL Server Agent (MSSQLSERVER) SqlAgent Auto Running
I don't have a SQL Server 2014 or later instance that I can safely test against, unfortunately.
I'm not sure if I'm getting version 14 of the assemblies from Microsoft's SqlServer PowerShell module from the PowerShell Gallery, or if I'm getting it from SSMS v17.
I actually have v10 of the assemblies still available on my system, and they work just like the v12 assemblies do.
I wonder if this is a bug or known issue.
this approach solves my problem.
I check the loaded assemblies with this command:
$dlls = [System.AppDomain]::CurrentDomain.GetAssemblies()
$dlls | where {$_.Location -match "SQL"}
I believe, I have found a solution for the most cases (Windows Server 2008-2012R2, SQL Server 2008-2014).
Add-Type -path "C:\Program Files (x86)\Microsoft SQL Server\$version\SDK\Assemblies\Microsoft.SqlServer.Smo.dll"
Add-Type -path "C:\Program Files (x86)\Microsoft SQL Server\$version\SDK\Assemblies\Microsoft.SqlServer.SqlWmiManagement.dll"
Sometimes the path is different. Sometimes the correct dlls are in the directory, which was specified as INSTALLSHAREDWOWDIR while installation.
Maybe aftermaths of an inplace-upgrade or installation of a new management studio.
More recent servers (Windows Server 2016, SQL Server 2016/2017) works great with [void][reflection.assembly]::LoadWithPartialName("Microsoft.SqlServer.Smo"), ...
I am using inno setup to install SQL Server with Database and Wildfly in two different machines (Machine A and Machine B) in a network respectively.
As a first step, I install any one SQL Server (2012, 2014 or 2016 versions) in Machine A.
In second step, I install Wildfly 10 in Machine B and during the installation I have a page where the user inputs the name of Database Server name, Database name and Instance name.
In order to verify the above entries, I have to validate that the Database name and Instance name is available in the Database server.
I was able to connect to the registry of the remote Machine B from Machine A to get the instance name installed using Power shell command with the below query
Invoke-Command -ComputerName MachineB -Command {Get-ItemProperty 'HKLM:\Software\Microsoft\Microsoft SQL Server\Instance Names\SQL'}
However, I could not find the list of databases installed in the registry.
Is there any way to get the list of databases available in the machine so that I can validate the same?
Sql Server does not store database names in the registry. Query sys.databases for db names. Like so,
Invoke-Sqlcmd -ServerInstance myServer\myInstance -Query "select name from sys.databases"
In order to use Invoke-SqlCmd on a system that doesn't have Sql Server installed, install Sql Server Powershell module to the local system.
I am trying to restore a database to a VM as part of a new VM provisioning process. However, when I try the following command to restore the database:
Restore-SqlDatabase -ServerInstance . -Database SomeDatabase -BackupFile $latestBackup -ReplaceDatabase
It fails with the error:
Restore-SqlDatabase : System.Data.SqlClient.SqlError: Directory lookup for the file "C:\Program Files\Microsoft SQL Server\MSSQL10.MSSQLSERVER\MSSQL\DATA\SomeDatabase.mdf" failed with the operating system error 3(The system cannot find the path specified.).
At line:27 char:1
+ Restore-SqlDatabase -ServerInstance . -Database SomeDatabase -BackupFile $latestB ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [Restore-SqlDatabase], SmoException
+ FullyQualifiedErrorId : ExecutionFailed,Microsoft.SqlServer.Management.PowerShell.RestoreSqlDatabaseCommand
This is confusing, since using SQL Server 2014 has the exact same path, but at MSSQL12.MSSQLSERVER instead of the MSSQL10.MSSQLSERVER that the Restore-SqlDatabase cmdlet is looking for. A database with the correct name already exists at the MSSQL12.MSSQLSERVER location as well.
How can I tell the cmdlet to restore it to the right folder?
You can do it by specifying the files locations as objects and passing them to Restore-SQLDatabase with the -RelocateFile parameter
$RelocateData = New-Object Microsoft.SqlServer.Management.Smo.RelocateFile("MainDB_Data", "c:\MySQLServer\MainDB.mdf")
$RelocateLog = New-Object Microsoft.SqlServer.Management.Smo.RelocateFile("MainDB_Log", "c:\MySQLServer\MainDB.ldf")
Restore-SqlDatabase -ServerInstance "Computer\Instance" -Database "MainDB" -BackupFile "\\mainserver\databasebackup\MainDB.trn" -RelocateFile #($RelocateData,$RelocateLog)
https://technet.microsoft.com/en-us/library/mt683379%28v=sql.120%29.aspx
Turns out it isn't really possible (that I could find) to restore a database like this. I reverted the VM to use a matching SQL server, and used the following command to restore the database:
Invoke-Sqlcmd -Query "RESTORE DATABASE [SomeDatabase] FROM DISK = N'C:\$latestBackup' WITH FILE = 1, MOVE N'SomeDatabase' TO N'C:\Program Files\Microsoft SQL Server\MSSQL10_50.MSSQLSERVER\MSSQL\DATA\SomeDatabase.mdf', MOVE N'SomeDatabase_log' TO N'C:\Program Files\Microsoft SQL Server\MSSQL10_50.MSSQLSERVER\MSSQL\DATA\SomeDatabase.ldf', NOUNLOAD, STATS = 10"
This was obtained via SQL Server Management Studio's "Script" functionality, where I set up the restore and exported the equivalent SQL.
I'm using sqlps powershell module to get some data from my local database. My code is something like this
PS C:\> Import-Module sqlps -DisableNameChecking
PS SQLSERVER:\> cd "SQL\myMachineName\..."
It works correctly, but sometimes I need to connect to a remote server running SQL server, so I use Enter-PSSession. Is this the correct way or can I somehow map that server under local SQLSERVER:\SQL directory?
The PowerShell provider for SQL server can be used to connect to a remote SQL server without PowerShell remoting. For example, at the SQLSERVER: drive, you can change the location to a different SQL Server using
PS SQLSERVER:\> cd "SQL\remoteMachineName\SQLInstanceName"
I tried to backup my database following the instruction from SQL Server: Database stuck in "Restoring" state. but i have my database stuck in "Restoring" state. php code below:
$database = "container";
$uid = "sa";
$pwd = "12345" ;
try {
$conn = new PDO( "sqlsrv:Server=localhost\SQLEXPRESS;Database=$database",
$uid,
$pwd
//,array(PDO::ATTR_PERSISTENT => true)
);
$conn->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION ); }
catch( PDOException $e ) {
die( "Error connecting to SQL Server" ); }
echo "Connected to SQL Server\n";
$backfile = 'C:\Program Files\Microsoft SQL Server\MSSQL.1\MSSQL\Backup\sql server bk' ;
echo "Connected to SQL Server\n";
$backfile = 'C:\Program Files\Microsoft SQL Server\MSSQL.1\MSSQL\Backup\sql server bk' ;
$query = "RESTORE DATABASE child_database FROM DISK = '$backfile' WITH REPLACE, RECOVERY ";
$conn->exec($query);
After running this code I got my child_database stuck in restoring state.however I copy the sql command
RESTORE DATABASE child_database FROM DISK = 'C:\Program Files\Microsoft SQL Server\MSSQL.1\MSSQL\Backup\sql server bk' WITH REPLACE, RECOVERY
and run in microsoft sql server management tool it works just fine.
I try to run add php code
$conn->exec("RESTORE DATABASE child_database WITH RECOVERY");
I got an exception.
please help.
It seems have problem with PDO driver, this problem may be in the ODBC/SNAC layer on which the driver is built. But this database restoring works well with other drivers.
I tried with sqlsrv and mssql, they worked well.
For more detail, see Restoring a SQL Server Database from PHP