SQL 2014 Database Set State

Microsoft.SQLServer.2014.SetDBState (WriteActionModuleType)

This module type is used to change the state of a Microsoft SQL Server 2014 Database. It takes configuration regarding the database to alter and the state to set.

Element properties:

TypeWriteActionModuleType
IsolationAny
AccessibilityInternal
RunAsMicrosoft.SQLServer.2014.SecureReference.Task
InputTypeSystem.BaseData

Member Modules:

ID Module Type TypeId RunAs 
WA WriteAction Microsoft.Windows.ScriptWriteAction Default

Overrideable Parameters:

IDParameterTypeSelectorDisplay NameDescription
TimeoutSecondsint$Config/TimeoutSeconds$Timeout (seconds)Specifies the time the workflow is allowed to run before being closed and marked as failed.

Source Code:

<WriteActionModuleType ID="Microsoft.SQLServer.2014.SetDBState" Accessibility="Internal" RunAs="SQL2014Core!Microsoft.SQLServer.2014.SecureReference.Task">
<Configuration>
<xsd:element xmlns:xsd="http://www.w3.org/2001/XMLSchema" name="ConnectionString" type="xsd:string"/>
<xsd:element xmlns:xsd="http://www.w3.org/2001/XMLSchema" name="Database" type="xsd:string"/>
<xsd:element xmlns:xsd="http://www.w3.org/2001/XMLSchema" name="State" type="xsd:string"/>
<xsd:element xmlns:xsd="http://www.w3.org/2001/XMLSchema" name="TimeoutSeconds" type="xsd:int"/>
</Configuration>
<OverrideableParameters>
<OverrideableParameter ID="TimeoutSeconds" ParameterType="int" Selector="$Config/TimeoutSeconds$"/>
</OverrideableParameters>
<ModuleImplementation>
<Composite>
<MemberModules>
<WriteAction ID="WA" TypeID="Windows!Microsoft.Windows.ScriptWriteAction">
<ScriptName>SetSQL2014DBState.js</ScriptName>
<Arguments>"$Config/ConnectionString$" "$Target/Host/Property[Type="SQL2014Core!Microsoft.SQLServer.2014.DBEngine"]/TcpPort$" "$Config/Database$" "$Config/State$" "$Target/Host/Host/Property[Type="Windows!Microsoft.Windows.Computer"]/NetworkName$" "$Target/Host/Property[Type="SQL2014Core!Microsoft.SQLServer.2014.ServerRole"]/InstanceName$"</Arguments>
<ScriptBody><Script>//#Include File:Common.js
var Common = function () {
arguments.callee.setAlias('Common.constructor');
this.DEBUG = false;
this.ManagementGroupName = "$Target/ManagementGroup/Name$";
this.ManagementGroupID = "$Target/ManagementGroup/Id$";

this.EscapeConnStringValue = function (connStringValue) {
return '"' + connStringValue.replace(/"/g, '""') + '"';
};

this.EscapeWQLString = function (wqlString) {
return wqlString.replace(/'/g, "\\'");
};

this.BuildConnectionString = function (server, database) {
var dataSource = this.BuildServerName(server);
return "Data Source=" + this.EscapeConnStringValue(dataSource) + ";Initial Catalog=" + this.EscapeConnStringValue(database) + ";Integrated Security=SSPI";
};

this.BuildConnectionStringWithPort = function (server, database, tcpPort) {
var dataSource = server;
if ((tcpPort !== "") &amp;&amp; (tcpPort !== "0")) {
dataSource = dataSource + "," + tcpPort;
}
return "Data Source=" + this.EscapeConnStringValue(dataSource) + ";Initial Catalog=" + this.EscapeConnStringValue(database) + ";Integrated Security=SSPI";
};

this.ConcatinateServerName = function (server, tcpPort) {
var dataSource = server;
if ((tcpPort !== "") &amp;&amp; (tcpPort !== "0")) {
dataSource = dataSource + "," + tcpPort;
}
return dataSource;
};

this.BuildServerName = function (strServer) {
var tcp = "";
var ip = "";
var pathArray = strServer.split("\\");
var instanceName = "MSSQLSERVER";
if (pathArray.length &gt; 1) {
instanceName = pathArray[1];
}

var serverName = strServer;

var oWMIcommon = new WMIProvider("root\\Microsoft\\SqlServer\\ComputerManagement12");
var oQuery = oWMIcommon.ExecQuery("SELECT * FROM ServerNetworkProtocolProperty WHERE ProtocolName = 'Tcp' AND InstanceName = '" + this.EscapeWQLString(instanceName) + "' AND PropertyName = 'ListenOnAllIPs'");

if (oQuery.Count &gt; 0) {
var e = new Enumerator(oQuery);
e.moveFirst();
var isListenAll = e.item();
if (isListenAll.PropertyNumVal === 1) {
oQuery = oWMIcommon.ExecQuery("SELECT * FROM ServerNetworkProtocolProperty WHERE ProtocolName = 'Tcp' AND InstanceName = '" + this.EscapeWQLString(instanceName) + "' AND IPAddressName = 'IPAll' AND (PropertyName = 'TcpPort' OR PropertyName = 'TcpDynamicPorts') AND PropertyStrVal != ''");
if (oQuery.Count &gt; 0) {
e = new Enumerator(oQuery);
e.moveFirst();
tcp = e.item().PropertyStrVal;
if ((tcp !== "0") &amp;&amp; (tcp !== "")) {
serverName = serverName + "," + tcp;
}
}
} else {
oQuery = oWMIcommon.ExecQuery("SELECT * FROM ServerNetworkProtocolProperty WHERE ProtocolName = 'Tcp' AND InstanceName = '" + this.EscapeWQLString(instanceName) + "' AND IPAddressName != '' AND PropertyName = 'Enabled' AND PropertyNumVal = 1");
if (oQuery.Count &gt; 0) {
var ipAddressName = oQuery.ItemIndex(0).IPAddressName;
oQuery = oWMIcommon.ExecQuery("SELECT * FROM ServerNetworkProtocolProperty WHERE ProtocolName = 'Tcp' AND InstanceName = '" + this.EscapeWQLString(instanceName) + "' AND IPAddressName = '" + this.EscapeWQLString(ipAddressName) + "' AND (PropertyName = 'TcpPort' OR PropertyName = 'TcpDynamicPorts') AND PropertyStrVal != ''");
if (oQuery.Count &gt; 0) {
e = new Enumerator(oQuery);
e.moveFirst();
tcp = e.item().PropertyStrVal;
}
oQuery = oWMIcommon.ExecQuery("SELECT * FROM ServerNetworkProtocolProperty WHERE ProtocolName = 'Tcp' AND InstanceName = '" + this.EscapeWQLString(instanceName) + "' AND IPAddressName = '" + this.EscapeWQLString(ipAddressName) + "' AND PropertyName = 'IpAddress' AND PropertyStrVal != ''");
if (oQuery.Count &gt; 0) {
e = new Enumerator(oQuery);
e.moveFirst();
ip = e.item().PropertyStrVal;
}
if (ip !== "") {
serverName = ip;
}
if (tcp !== "") {
serverName = serverName + "," + tcp;
}
}
}
}
return serverName;
};

this.CheckConnectionTarget = function (dbConnection, serverName, instanceName) {
var destinationTestQuery = "select SERVERPROPERTY('MachineName') as ServerName, @@servicename as InstanceName";
var queryResult = dbConnection.ExecuteQuery(destinationTestQuery);
queryResult.MoveFirst();
if (!queryResult.EOF) {
var queryServerName = queryResult("ServerName").Value.toUpperCase();
var queryInstanceName = queryResult("InstanceName").Value.toUpperCase();
var serverNameWithoutDomain = serverName;
var dotPosition = serverName.indexOf(".");
if (dotPosition &gt; -1) {
serverNameWithoutDomain = serverName.substring(0, dotPosition);
}
if (serverNameWithoutDomain.toUpperCase() == queryServerName &amp;&amp; instanceName.toUpperCase() == queryInstanceName) {
return;
}
}
throw new Exception("Connection target check failed: connected to " + serverName + "\\" + instanceName + ", but got " + queryServerName + "\\" + queryInstanceName + ".");
};

this.SmartConnect = function (serverName, databaseName, tcpPort, machineName, instanceName) {
var dbMasterConnection;
var connectionString;
//try to use SQL server browser
connectionString = this.BuildConnectionStringWithPort(serverName, databaseName, "");
try {
dbMasterConnection = new ADODB(connectionString, "sqloledb", 10);
this.CheckConnectionTarget(dbMasterConnection, machineName, instanceName);
} catch (e) {
//use original tcp port and try to connect again
connectionString = this.BuildConnectionStringWithPort(serverName, databaseName, tcpPort);
try {
dbMasterConnection = new ADODB(connectionString, "sqloledb", 10);
this.CheckConnectionTarget(dbMasterConnection, machineName, instanceName);
} catch (eInt) {
//get fresh tcp port and try to connect again
connectionString = this.BuildConnectionString(serverName, databaseName);
dbMasterConnection = new ADODB(connectionString, "sqloledb", 30);
this.CheckConnectionTarget(dbMasterConnection, machineName, instanceName);
}
}
return dbMasterConnection;
};
};

Function.prototype.setAlias = function (funcName) {
this.getAlias = function () {
return funcName;
};
};

Error.prototype.toString = function () {
if (this.message) {
var parts = [];
parts.push(this.message);
parts.push('\n');

if (this.number) {
parts.push("Error Number : ");
parts.push(this.number);
parts.push('\n');
parts.push("Error Code : ");
parts.push(this.number &amp; 0xFFFF);
parts.push('\n');
parts.push("Win32 Facility : ");
parts.push((this.number &gt;&gt; 16 &amp; 0x1FFF));
parts.push('\n');
}
if (this.description) {
parts.push("Error Description : ");
parts.push(this.description);
}
parts.push('\n');
return parts.join('');
} else {
return this.toString();
}
};

var Exception = function (message, innerException) {
arguments.callee.setAlias('Exception.constructor');
this.message = message;
this.innerException = innerException;

var parts = [];
var collectArguments = function (caller) {
parts.push('(');
for (var i = 0; i &lt; caller.length; i++) {
if (typeof (caller[i]) !== 'undefined') {
parts.push(caller[i] === null ? 'null' : (typeof (caller[i].toString) === 'undefined' ? 'Object' : caller[i].toString()));
parts.push(',');
}
}
parts.pop();
parts.push(')');
parts.push(',\n');
};
var collectCallStack = function (caller) {
arguments.callee.setAlias('Exception.collectCallStack');
parts.push(caller.callee.getAlias ? caller.callee.getAlias() : 'anonymous');
collectArguments(caller);
var nextCaller = caller.caller;
if (nextCaller) {
collectCallStack(nextCaller);
}
};
collectCallStack(arguments);
this.callStack = parts.join('');

this.toString = function () {
arguments.callee.setAlias('Exception.toStringFull');
var toStringParts = [];
toStringParts.push(this.message);
toStringParts.push('\n');
if (this.innerException) {
if (this.innerException.number || this.innerException.description) {
toStringParts.push('Inner exception: \n');
if (this.innerException.number) {
toStringParts.push("Error Number : ");
toStringParts.push(this.innerException.number);
toStringParts.push('\n');
toStringParts.push("Error Code : ");
toStringParts.push(this.innerException.number &amp; 0xFFFF);
toStringParts.push('\n');
toStringParts.push("Win32 Facility : ");
toStringParts.push((this.innerException.number &gt;&gt; 16 &amp; 0x1FFF));
toStringParts.push('\n');
}
if (this.innerException.description) {
toStringParts.push("Error Description : ");
toStringParts.push(this.innerException.description);
toStringParts.push('\n');
}
}
}
toStringParts.push('Call stack:');
toStringParts.push(this.callStack);
return toStringParts.join('');
};
};

var OpsMgrAPI = function () {
arguments.callee.setAlias('MOMAPI.constructor');
var scriptAPI;
try {
scriptAPI = new ActiveXObject('MOM.ScriptAPI');
} catch (e) {
throw new Exception("Application cannot create MOM.ScriptAPI ActiveX object.", e);
}
this.ScriptAPI = scriptAPI;
};



var Logger = function () {
arguments.callee.setAlias('Logger.constructor');
this.common = new Common();
this.messageType = {
error: 1,
warning: 2,
information: 4
};

var opsMgrAPI = new OpsMgrAPI();

this.LogError = function (eventId, logMessage) {
arguments.callee.setAlias('Logger.LogError');
opsMgrAPI.ScriptAPI.LogScriptEvent("Management Group: " + this.common.ManagementGroupName + ". Script: " + WScript.ScriptName, eventId, this.messageType.error, logMessage);
};
this.LogError2 = function (instanceName, eventId, logMessage) {
arguments.callee.setAlias('Logger.LogError2');
opsMgrAPI.ScriptAPI.LogScriptEvent("Management Group: " + this.common.ManagementGroupName + ". Script: " + WScript.ScriptName+". Instance: " + instanceName, eventId, this.messageType.error, logMessage);
};
this.LogWarning = function (eventId, logMessage) {
arguments.callee.setAlias('Logger.LogWarning');
opsMgrAPI.ScriptAPI.LogScriptEvent("Management Group: " + this.common.ManagementGroupName + ". Script: " + WScript.ScriptName, eventId, this.messageType.warning, logMessage);
};
this.LogInformation = function (eventId, logMessage) {
arguments.callee.setAlias('Logger.LogInformation');
opsMgrAPI.ScriptAPI.LogScriptEvent("Management Group: " + this.common.ManagementGroupName + ". Script: " + WScript.ScriptName, eventId, this.messageType.information, logMessage);
};
this.LogDebug = function (eventId, logMessage) {
if (this.common.DEBUG) {
arguments.callee.setAlias('Logger.LogDebug');
opsMgrAPI.ScriptAPI.LogScriptEvent("Management Group: " + this.common.ManagementGroupName + ". Script: " + WScript.ScriptName, eventId, this.messageType.information, logMessage);
}
};
this.LogCustomInfo = function (param1, eventId, logMessage) {
arguments.callee.setAlias('Logger.LogCustomInfo');
opsMgrAPI.ScriptAPI.LogScriptEvent(param1, eventId, this.messageType.information, logMessage);
};
};

var ADODB = function (connectionString, provider, connectionTimeout) {
arguments.callee.setAlias('ADODB.constructor');
if (!connectionString) {
throw new Exception("Connection string cannot be null or empty string");
}
this.provider = provider ? provider : "sqloledb";
this.connectionTimeout = connectionTimeout ? connectionTimeout : 30;

var connection;
try {
connection = new ActiveXObject("ADODB.Connection");
} catch (e) {
throw new Exception("Can't create ActiveXObject 'ADODB.Connection'", e);
}

connection.Provider = this.provider;
connection.ConnectionTimeout = this.connectionTimeout;
connection.ConnectionString = connectionString;
try {
connection.Open();
} catch (e) {
throw new Exception("Can't connect to SQL Server. Connection string : '" + connectionString + "'", e);
}

this.ExecuteQuery = function (query) {
arguments.callee.setAlias('ADODB.ExecuteQuery');
var dbSet;
try {
dbSet = connection.Execute(query);
} catch (e) {
throw new Exception("Can't execute query '" + query + "'", e);
}
return dbSet;
};

this.ExecuteQueryWithParams = function (query) {
arguments.callee.setAlias('ADODB.ExecuteQueryWithParams');
if (arguments.length &lt;= 1) {
throw new Exception("Can't go without any params");
}
var dbSet;
try {
var command = new ActiveXObject("ADODB.Command");
command.ActiveConnection = connection;
command.CommandText = query;
command.CommandType = 1; // adCmdText
for (var i = 1; i &lt; arguments.length; i++) {
this.AddParam(command, arguments[i]);
}
dbSet = command.Execute();
} catch (e) {
throw new Exception("Can't execute query '" + query + "'", e);
}
return dbSet;
};

this.AddParam = function (cmd, value) {
var parameter;
switch (typeof value) {
case "number":
parameter = cmd.CreateParameter("", 20, 1, 8, value); // , adBigInt, adParamInput
break;
case "string":
parameter = cmd.CreateParameter("", 202, 1, Math.max(value.length, 1), value); // , adVarWChar, adParamInput
break;
default:
throw new Exception("Unknown parameter type: " + typeof value);
}
cmd.Parameters.Append(parameter);
};

this.Close = function () {
arguments.callee.setAlias('ADODB.Close');
try {
if (connection) {
connection.Close();
}
}
catch (e) {
throw new Exception("Can't close connection.", e);
}
};
};

var Registry = function () {
arguments.callee.setAlias('Registry.constructor');
var registry;
try {
registry = new ActiveXObject("WScript.Shell");
} catch (e) {
throw new Exception("Can't create ActiveXObject 'WScript.Shell'", e);
}

this.Write = function (key, value, type) {
arguments.callee.setAlias('Registry.Write');
try {
if (type) {
registry.RegWrite(key, value, type);
} else {
registry.RegWrite(key, value);
}
} catch (e) {
throw new Exception("Can't write value '" + value.toString() + "' by registry key '" + key.toString() + "'.", e);
}
};
this.Read = function (key) {
arguments.callee.setAlias('Registry.Read');
var value;
try {
value = registry.RegRead(key);
} catch (e) {
throw new Exception("Can't read value from registry key '" + key.toString() + "'.", e);
}
return value;
};
this.IsKeyExists = function (key) {
arguments.callee.setAlias('Registry.IsKeyExists');
var result;
try {
registry.RegRead(key);
result = true;
} catch (e) {
result = false;
}
return result;
};
this.Delete = function (key) {
arguments.callee.setAlias('Registry.Delete');
var value;
try {
value = registry.RegDelete(key);
} catch (e) {
throw new Exception("Can't delete registry key '" + key.toString() + "'.", e);
}
return value;
};
};

var WMIProvider = function (wmiNamespace, computerName) {
arguments.callee.setAlias('WMIProvider.constructor');
this.wmiNamespace = wmiNamespace;
this.computerName = (!computerName) ? computerName : ".";
var sWbemLocator;
try {
sWbemLocator = new ActiveXObject("WbemScripting.SWbemLocator");
} catch (e) {
throw new Exception("Cannot create 'WbemScripting.SWbemLocator' object.", e);
}
this.SWbemLocator = sWbemLocator;

var wmiService;
try {
wmiService = this.SWbemLocator.ConnectServer(this.computerName, this.wmiNamespace);
} catch (e) {
throw new Exception("Cannot connect to WMI of computer '" + this.computerName + "' by namespace '" + this.wmiNamespace + "'.", e);
}
this.WMIService = wmiService;

this.ExecQuery = function (query) {
arguments.callee.setAlias('WMIProvider.ExecQuery');
var result = null;
try {
result = this.WMIService.ExecQuery(query, "WQL", 0x0);
} catch (e) {
throw new Exception("Cannot execute WMI query '" + query + "'.", e);
}
return result;
};
};

var DBHelper = function () {
arguments.callee.setAlias('DBHelper.constructor');
this.EVENT_ID = 4201;
this.DatabaseState = {
emergencyMode: 32768,
loading: 22,
normal: 0,
offline: 512,
recovering: 192,
standby: 1024,
suspect: 256
};
this.common = new Common();
this.logger = new Logger();

this.IsRunningInstanceSQLServer = function (sqlInstanceName) {
arguments.callee.setAlias('IsRunningInstanceSQLServer');
var isRunning = false;
try {
var wmiProvider = new WMIProvider("root\\Microsoft\\SqlServer\\ComputerManagement12");
var sqlService = wmiProvider.ExecQuery("select state from SqlService WHERE (ServiceName = '" + this.common.EscapeWQLString(sqlInstanceName) + "' OR ServiceName = 'MSSQL$" + this.common.EscapeWQLString(sqlInstanceName) + "') and SQLServiceType ='1'");

if (sqlService.Count &gt; 0) {
var e = new Enumerator(sqlService);
e.moveFirst();
var sqlServiceObject = e.item();

if (sqlServiceObject.State === 4) {
isRunning = true;
}
}
} catch (exception) {
}
return isRunning;
};

this.GetDatabaseExcludeList = function (instanceName) {
arguments.callee.setAlias('GetDatabaseExcludeList');
var databaseExcludeList = "";
try {
var opsMgrAPI = new OpsMgrAPI();
var registryKey = opsMgrAPI.ScriptAPI.GetScriptStateKeyPath(this.common.ManagementGroupID);
this.logger.LogDebug(this.EVENT_ID, "ScriptStateKeyPath: " + registryKey);

var registry = new Registry();
var databaseExcludeListKey = "HKEY_LOCAL_MACHINE\\" + registryKey + "\\" + instanceName + "\\DatabaseExcludeList";
if (registry.IsKeyExists(databaseExcludeListKey)) {
databaseExcludeList = registry.Read(databaseExcludeListKey);
databaseExcludeList = databaseExcludeList.replace(/(^\s+)|(\s+$)/g, "");
if (databaseExcludeList !== '*') {
var excludeDatabases = databaseExcludeList.split(",");
for (var i = 0; i &lt; excludeDatabases.length; i++) {
excludeDatabases[i] = excludeDatabases[i].replace(/(^\s+)|(\s+$)/g, "");
}
databaseExcludeList = excludeDatabases.join(",");
}
}
} catch (e) {
throw new Exception("Can't read database exclude list from registry.", e);
}
return databaseExcludeList;
};

// Returns -1: If DB is not in AlwaysOn
// Returns 0: If DB is in AlwaysOn and replica allow connections is NO
// Returns 1: If DB is in AlwaysOn and replica allow connections is YES
this.AlwaysOnReplicaAllowConnections = function (aDbConnection, aDatabaseID) {
var query = " SELECT columns.id, " +
" CASE WHEN OBJECT_ID('sys.availability_replicas') IS NOT NULL THEN 1 ELSE 0 END AS HasAlwaysOn " +
" FROM sys.syscolumns columns where name = 'replica_id' and id = OBJECT_ID('sys.databases')";

var result = aDbConnection.ExecuteQuery(query);
if (!result.EOF) {
result.MoveFirst();
if (result("HasAlwaysOn").Value === 1) {
query = " SELECT d.name, d.database_id, " +
" CASE WHEN d.replica_id IS NULL THEN 0 ELSE 1 END AS is_replica, " +
" ar.secondary_role_allow_connections " +
" FROM sys.databases d " +
" JOIN sys.availability_replicas ar on d.replica_id = ar.replica_id " +
" JOIN sys.servers s ON s.name = ar.replica_server_name AND s.server_id = 0 /*local server*/" +
" WHERE d.database_id = ? ";

result = aDbConnection.ExecuteQueryWithParams(query, aDatabaseID);
if (!result.EOF) {

if (result("is_replica").Value === 1) {
if (result("secondary_role_allow_connections").Value &lt;= 1) {
return 0;
} else {
return 1;
}
}
}
}
}

return -1;
};
};

var ServicesHelper = function () {
arguments.callee.setAlias('ServicesHelper.constructor');

this.EVENT_ID = 4201;
this.IsServiceUnavailable = "ServiceUnavailable";
this.logger = new Logger();
this.common = new Common();

this.GetServiceUnavailableRegistryKey = function (serviceName) {
arguments.callee.setAlias('GetRegistryKeyForService');
var opsMgrAPI = new OpsMgrAPI();
var registryKey = opsMgrAPI.ScriptAPI.GetScriptStateKeyPath(this.common.ManagementGroupID);
var key = "HKEY_LOCAL_MACHINE\\" + registryKey + "\\" + serviceName + "\\";
return key;
};

this.ReturnServiceStateToOpsMgr = function (serviceState) {
var opsMgrAPI = new OpsMgrAPI();
this.logger.LogDebug(this.EVENT_ID, "Return to OpsMgr state of service = " + serviceState);
var propertyBag = opsMgrAPI.ScriptAPI.CreatePropertyBag();
propertyBag.AddValue("ServiceState", serviceState);
opsMgrAPI.ScriptAPI.AddItem(propertyBag);
opsMgrAPI.ScriptAPI.ReturnItems();
};
};
//#Include File:SetSQL2014DBState.js

var SetSQL2014DBState = function () {
arguments.callee.setAlias('SetSQL2014DBState.constructor');

this.common = new Common();
this.ADOConnectionTimeout = 30;
this.SCRIPT_CONNECT_FAILURE_MSG = "Could not connect to SQL";

this.EscapeDBName = function (strValue) {
return strValue.replace(/]/g, "]]");
};

this.SetDBState = function (connectionString, tcpPort, databaseName, databaseState, targetComputer, instanceName) {
var sqlServer;
try {
sqlServer = this.common.SmartConnect(connectionString, "master", tcpPort, targetComputer, instanceName);
} catch (e) {
this.PrintError(e);
this.FailScript(e, this.SCRIPT_CONNECT_FAILURE_MSG);
}
if (sqlServer) {
try {
var sqlQuery = "ALTER DATABASE [" + this.EscapeDBName(databaseName) + "] SET " + databaseState;
WScript.Echo("Executing Query: '" + sqlQuery + "' for instance: '" + connectionString + "'");
sqlServer.ExecuteQuery(sqlQuery);
} catch (e) {
this.PrintError(e);
this.FailScript(e, this.SCRIPT_CONNECT_FAILURE_MSG);
}
}
};

this.PrintError = function (error) {
WScript.Echo("============================= BEGIN SCRIPT ERROR =================================\n");
WScript.Echo("Script Name : " + WScript.ScriptName);
WScript.Echo("Error Type : " + error);
WScript.Echo("Error Number : " + error.number);
WScript.Echo("Error Code : " + (error.number &amp; 0xFFFF).toString());
WScript.Echo("Win32 Facility : " + (error.number &gt;&gt; 16 &amp; 0x1FFF).toString());
WScript.Echo("Error Source : " + error.Source);
WScript.Echo("Error Description : " + error.description + "\n");
WScript.Echo("============================== END SCRIPT ERROR ==================================\n");
};

this.FailScript = function (error, sMessage) {
var opsmgrAPI = new ActiveXObject("MOM.ScriptAPI");
opsmgrAPI.LogScriptEvent("SetSQL2014DBState.js", 4201, 1, sMessage + ". " + error.description);
};

this.Launch = function (args) {
if (args.Length !== 6) {
WScript.Quit();
}
var connectionString = args(0);
var tcpPort = args(1);
var databaseName = args(2);
var databaseState = args(3);
var targetComputer = args(4);
var instanceName = args(5);

this.SetDBState(connectionString, tcpPort, databaseName, databaseState, targetComputer, instanceName);
};
};

new SetSQL2014DBState().Launch(WScript.Arguments);
</Script></ScriptBody>
<TimeoutSeconds>$Config/TimeoutSeconds$</TimeoutSeconds>
</WriteAction>
</MemberModules>
<Composition>
<Node ID="WA"/>
</Composition>
</Composite>
</ModuleImplementation>
<InputType>System!System.BaseData</InputType>
</WriteActionModuleType>