Protected Endpoint Candidate Data Source

Microsoft.FEP.ProtectedServerCandidate.DS (DataSourceModuleType)

Element properties:

TypeDataSourceModuleType
IsolationAny
AccessibilityPublic
RunAsDefault
OutputTypeSystem.Discovery.Data

Member Modules:

ID Module Type TypeId RunAs 
ProtectedServerCandidateDS DataSource Microsoft.Windows.TimedScript.DiscoveryProvider Default

Overrideable Parameters:

IDParameterTypeSelectorDisplay NameDescription
IntervalSecondsint$Config/IntervalSeconds$Scan Interval (Seconds)This parameter defines the interval (in seconds) that this discovery is gathering the protected endpoint data. The default value is 28800, at which the discovery will gather the protected endpoint data every 8 hours.
TimeoutSecondsint$Config/TimeoutSeconds$Timeout (Seconds)

Source Code:

<DataSourceModuleType ID="Microsoft.FEP.ProtectedServerCandidate.DS" Accessibility="Public" Batching="false">
<Configuration>
<IncludeSchemaTypes>
<SchemaType>System!System.Discovery.MapperSchema</SchemaType>
</IncludeSchemaTypes>
<xsd:element name="ServerId" type="xsd:string"/>
<xsd:element minOccurs="1" name="IntervalSeconds" type="xsd:positiveInteger"/>
<xsd:element minOccurs="1" name="TimeoutSeconds" type="xsd:positiveInteger"/>
<xsd:element minOccurs="1" name="OperatingSystem">
<xsd:simpleType>
<xsd:restriction base="xsd:string">
<xsd:enumeration value="Windows Client"/>
<xsd:enumeration value="Windows Server"/>
</xsd:restriction>
</xsd:simpleType>
</xsd:element>
</Configuration>
<OverrideableParameters>
<OverrideableParameter ID="IntervalSeconds" Selector="$Config/IntervalSeconds$" ParameterType="int"/>
<OverrideableParameter ID="TimeoutSeconds" Selector="$Config/TimeoutSeconds$" ParameterType="int"/>
</OverrideableParameters>
<ModuleImplementation Isolation="Any">
<Composite>
<MemberModules>
<DataSource ID="ProtectedServerCandidateDS" TypeID="Windows!Microsoft.Windows.TimedScript.DiscoveryProvider">
<IntervalSeconds>$Config/IntervalSeconds$</IntervalSeconds>
<SyncTime/>
<ScriptName>Microsoft.FEP.ProtectedServerCandidate.DS.vbs</ScriptName>
<Arguments>$MPElement$ $Target/Id$ $Config/ServerId$ "$Config/OperatingSystem$"</Arguments>
<ScriptBody><Script>
Option Explicit

Const ACTEXEC_CMD_ABORTSCAN = "abortscan"
Const ACTEXEC_CMD_APPLY_CCSETTS = "apply_cc_settings"
Const ACTEXEC_CMD_SCAN = "scan"
Const ACTEXEC_CMD_START_AMSERVICE = "start_service"
Const ACTEXEC_CMD_UNKNOWN = "unknown command"
Const ACTEXEC_CMD_UPDATE = "update"
Const AM_POLICY_BLOCKALL_INBOUND_TRAFFIC = "BlockAllInboundTraffic"
Const AM_POLICY_DEFAULTINBOUND_ACTION_ISDENY = "DefaultInboundActionIsDeny"
Const AM_POLICY_DISABLEBEHAVIOUR = "DisableBehaviorMonitoring"
Const AM_POLICY_DISABLEINBOUND_NOTIFICATIONS = "DisableInboundNotifications"
Const AM_POLICY_DISABLEONACCESSPROTECTION = "DisableOnAccessProtection"
Const AM_POLICY_DISABLERTM = "DisableRealtimeMonitoring"
Const AM_POLICY_DISABLESCRIPTSCANNING = "DisableScriptScanning"
Const AM_POLICY_DISABLE_IPS = "DisableIntrusionPreventionSystem"
Const AM_POLICY_ENABLEFIREWALL = "EnableFirewall"
Const AM_POLICY_REGKEY_ROOT = "SOFTWARE\Policies\Microsoft\Microsoft Antimalware"
Const AM_POLICY_RTSDIRECTION = "RealTimeScanDirection"
Const AM_POLICY_SIGNATURE_UPD_CATCHUP_INTERVAL = "SignatureUpdateCatchupInterval"
Const AM_POLICY_SIGNATURE_UPD_INTERVAL = "SignatureUpdateInterval"
Const AM_REGKEY_CLIENT_INSTKEY = "SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\Microsoft Security Client"
Const AM_REGKEY_EXCLUDED_EXTS = "\Exclusions\Extensions"
Const AM_REGKEY_EXCLUDED_PATHS = "\Exclusions\Paths"
Const AM_REGKEY_EXCLUDED_PROCESSES = "\Exclusions\Processes"
Const AM_REGKEY_FULL_SIGNATURE_UPDATES = "SOFTWARE\Policies\Microsoft\Microsoft Antimalware\Signature Updates"
Const AM_REGKEY_POLICY_RTP = "SOFTWARE\Policies\Microsoft\Microsoft Antimalware\Real-Time Protection"
Const AM_REGKEY_ROOT = "SOFTWARE\Microsoft\Microsoft Antimalware"
Const AM_REGKEY_SCAN = "\Scan"
Const AM_REGKEY_SIGNATURE_UPDATES = "\Signature Updates"
Const AM_REGKEY_SIG_UPDATES_POLICY = "SOFTWARE\Policies\Microsoft\Microsoft Antimalware\Signature Updates"
Const AM_REGVALUE_CLIENT_CONFIGPOLICY = "ConfigSecurityPolicy.exe"
Const AM_REGVALUE_CLIENT_INSTDATE = "InstallDate"
Const AM_REGVALUE_CLIENT_INSTLOCATION = "InstallLocation"
Const AM_REGVALUE_CLIENT_MPCMDRUN = "MpCmdRun.exe"
Const AM_REGVALUE_CLIENT_NAME = "DisplayName"
Const AM_REGVALUE_CLIENT_VERSION = "DisplayVersion"
Const AM_REGVALUE_SCANPARAMETERS = "ScanParameters"
Const AM_REGVALUE_SCHEDULEDAY = "ScheduleDay"
Const AM_REGVALUE_SCHEDULETIME = "ScheduleTime"
Const AM_REGVALUE_SCHEDULE_QUICK_SCAN_TIME = "ScheduleQuickScanTime"
Const AM_REGVALUE_SIGNATURE_DOWNLOAD_LOC = "FallbackOrder"
Const AM_RTPSTATUS_OFF = "Off"
Const AM_RTPSTATUS_ON = "On"
Const AM_RTS_DIRECTION_BOTH = "Both incoming and outgoing"
Const AM_RTS_DIRECTION_INCOMING = "Incoming"
Const AM_RTS_DIRECTION_OUTCOMING = "Outgoing"
Const AM_RTS_DIRECTION_UNKNOWN = "Unknown"
Const AM_SERVICE_NAME = "MsMpSvc"
Const AM_STATUS_DISABLED = "Disabled"
Const AM_STATUS_ENABLED = "Enabled"
Const AM_WMI_HEALTH_STATUS_QUERY = "Select * from AntimalwareHealthStatus"
Const AM_WMI_INFECT_STATUS_QUERY = "SELECT * FROM AntimalwareInfectionStatus"
Const AM_WMI_NAMESPACE = "winmgmts:\\.\root\Microsoft\SecurityClient"
Const CIMV2_WMI_NAMESPACE = "winmgmts:\\.\root\cimv2"
Const CLIENT_REGKEY_ROOT = "SOFTWARE\Microsoft\Microsoft Security Client"
Const DEPLOY_FAILED_HRESULT_CANCEL = "0x8004FF0A"
Const DEPLOY_FAILED_HRESULT_RESTART = "0x0004FF00"
Const DEPLOY_FAILED_HRESULT_RESTART2 = "0x8004FF25"
Const DEPLOY_FAILED_HRESULT_SUCCESS = "0x00000000"
Const DEPLOY_FAILED_MONITOR_CRITICAL = 3
Const DEPLOY_FAILED_MONITOR_HEALTHY = 1
Const DEPLOY_FAILED_MONITOR_WARNING = 2
Const DEPLOY_FAIL_ERROR_CODE_NAME = "DeploymentErrorCode"
Const DEPLOY_FAIL_INFO_NAME = "DeploymentInfo"
Const DEPLOY_FAIL_RESULT_NAME = "DeploymentResult"
Const DEPLOY_FAIL_STATE_NAME = "DeploymentState"
Const EVTLOG_MW_DETECTION_WMI_QUERY = "Select * from Win32_NTLogEvent WHERE Logfile = 'System' AND SourceName='Microsoft Antimalware' AND (EventCode='1119' OR EventCode='1118' OR EventCode='1117')"
Const FAILED_POLICY_DATE_REGKEY = "LastFailedToApplyPolicyTimeUTC"
Const FAILED_POLICY_ERR_DESC_REGKEY = "LastPolicyErrorMessage"
Const FAILED_POLICY_NAME_REGKEY = "LastFailedToApplyPolicy"
Const FEP_DEPLOYMENT_REBOOT_IS_NOT_REQUIRED = "No"
Const FEP_DEPLOYMENT_REBOOT_IS_REQUIRED = "Yes"
Const FEP_DEPLOY_ERROR_FILE_NAME = "EppSetupResult.ini"
Const FEP_DEPLOY_STATUS_FAILED = "Installation Failed"
Const FEP_DEPLOY_STATUS_INSTALLED = "Installed"
Const FEP_DEPLOY_STATUS_NO_INSTALL_DETECTED = "Never Installed"
Const FEP_DEPLOY_STATUS_REBOOT_REQUIRED = "Restart Required"
Const FEP_DEPLOY_STATUS_UNINSTALLED = "Uninstalled"
Const FEP_DEPLOY_STATUS_USER_CANCELED = "User Canceled Installation"
Const FEP_SUPPRT_DIR_PATH = "%ProgramData%\Microsoft\Microsoft Security Client\Support"
Const FEP_SUPPRT_XP_DIR_PATH = "%ALLUSERSPROFILE%\Application Data\Microsoft\Microsoft Security Client\Support"
Const FULL_SCAN = "Full scan"
Const FW_GENERIC_QUERY = "Select * from "
Const FW_POLICY_CLASS_PROF_DOMAIN = "Firewall_Profile_Domain"
Const FW_POLICY_CLASS_PROF_PRIVATE = "Firewall_Profile_Private"
Const FW_POLICY_CLASS_PROF_PUBLIC = "Firewall_Profile_Public"
Const FW_REGKEY_ROOT = "Root\Microsoft\PolicyPlatform\WindowsFirewallConfiguration"
Const FW_STATUS_OFF = "Off"
Const FW_STATUS_ON = "On"
Const FW_STATUS_UNINSTALLED = "Uninstalled"
Const FW_WMI_NAMESPACE = "winmgmts:{impersonationLevel=impersonate}!\\.\Root\Microsoft\PolicyPlatform\WindowsFirewallConfiguration"
Const FW_WMI_QUERY = "Select * from FirewallState"
Const LOG_REGKEY = "SOFTWARE\Microsoft\FEPS\Log"
Const LOG_REGVALUE_ENABLED = "Enabled"
Const LOG_SUBFOLDER_NAME = "FEP 2010 Security MP"
Const MPCMDRUN_CMD_FULLSCAN = " -scan -scantype 2"
Const MPCMDRUN_CMD_QUICKSCAN = " -scan -scantype 1"
Const MPCMDRUN_CMD_SIGUPDATE = " -SignatureUpdate"
Const NIS_STATUS_NOT_SUPPORTED = "Not Supported"
Const NIS_STATUS_NOT_UNKNOWN = "Unknown"
Const NIS_STATUS_OFF = "Off"
Const NIS_STATUS_ON = "On"
Const OS_REGKEY_ARCHITECTURE = "SYSTEM\CurrentControlSet\Control\Session Manager\Environment"
Const OS_REGVALUE_ARCHITECTURE = "PROCESSOR_ARCHITECTURE"
Const POLICY_DATE_REGKEY = "LastSuccessfullyAppliedPolicyTimeUTC"
Const POLICY_LOCAL_SETTINGS_OVERRIDE_PREFIX = "LocalSettingOverride"
Const POLICY_NAME = "SCOM applied FEP-S Policy"
Const POLICY_NAME_REGKEY = "LastSuccessfullyAppliedPolicy"
Const POLICY_SECTION_AM = "FEP.AmPolicy"
Const POLICY_SECTION_FW = "FEP.HostFirewallPolicy"
Const QUICK_SCAN = "Quick scan"
Const REG_VALUE_APPLIED_POLICY = "LastSuccessfullyAppliedPolicy"
Const REG_WMICLASS_PROVIDERNAME = "StdRegProv"
Const REG_WMI_NAMESPACE = "root\default"
Const RETRIEVAL_TITLE_ANTIMALWARE_ENGINE = "Antimalware Engine"
Const RETRIEVAL_TITLE_ANTISPYWARE_DEFINITIONS_AGE = "Antispyware Definitions Age (days)"
Const RETRIEVAL_TITLE_ANTISPYWARE_DEFINITIONS_VERSION = "Antispyware Definitions Version"
Const RETRIEVAL_TITLE_ANTISPYWARE_DEFINITIONS__DATE = "Antispyware Definitions Creation (GMT)"
Const RETRIEVAL_TITLE_ANTIVIRUS_DEFINITIONS_AGE = "Antivirus Definitions Age (days)"
Const RETRIEVAL_TITLE_ANTIVIRUS_DEFINITIONS_DATE = "Antivirus Definitions Creation (GMT)"
Const RETRIEVAL_TITLE_ANTIVIRUS_DEFINITIONS_VERSION = "Antivirus Definitions Version"
Const RETRIEVAL_TITLE_CLIENT_VERSION = "Client Version"
Const RETRIEVAL_TITLE_DOWNLOAD_LOCATION = "Definitions Download Location"
Const RETRIEVAL_TITLE_EXCLUDED_EXTENTIONS = "Excluded Extensions"
Const RETRIEVAL_TITLE_EXCLUDED_FOLDERS = "Excluded Folders"
Const RETRIEVAL_TITLE_EXCLUDED_PROCESSES = "Excluded Processes"
Const RETRIEVAL_TITLE_FAILED_POLICY_DATE = "Failed Policy Date"
Const RETRIEVAL_TITLE_FAILED_POLICY_DETAIL = "Policy Failure Details"
Const RETRIEVAL_TITLE_FAILED_POLICY_NAME = "Failed Policy Name"
Const RETRIEVAL_TITLE_FIREWALL = "Windows Firewall"
Const RETRIEVAL_TITLE_FULL_AGE = "Last Full Scan Age (days)"
Const RETRIEVAL_TITLE_FULL_END = "Last Full Scan End (GMT)"
Const RETRIEVAL_TITLE_FULL_START = "Last Full Scan Start (GMT)"
Const RETRIEVAL_TITLE_NIS = "NIS"
Const RETRIEVAL_TITLE_NIS_DEFINITIONS_VERSION = "NIS Definitions Version"
Const RETRIEVAL_TITLE_POLICY_DATE = "Policy Date"
Const RETRIEVAL_TITLE_POLICY_NAME = "Policy Name"
Const RETRIEVAL_TITLE_QUICK_AGE = "Last Quick Scan Age (days)"
Const RETRIEVAL_TITLE_QUICK_END = "Last Quick Scan End (GMT)"
Const RETRIEVAL_TITLE_QUICK_START = "Last Quick Scan Start (GMT)"
Const RETRIEVAL_TITLE_RTP = "Real-time Protection"
Const RETRIEVAL_TITLE_RTP_DIRECTION = "Real-time Protection Scan Direction"
Const RETRIEVAL_TITLE_SCAN_SCHDULE = "Scan schedule"
Const RETRIEVAL_TITLE_UPDATE_SCHEDULE = "Antimalware definitions update schedule"
Const SCHEDULE_DAILY = "Daily"
Const SCHEDULE_SCAN_SCHEDULE_STRING = "{0} around {1} ({2})"
Const SCHEDULE_SCAN_SCHEDULE_WITH_QUICK_STRING = "{0} around {1} ({2}); Quick scan daily around {3}"
Const SCHEDULE_UNDEFINED = "undefined"
Const TASK_ERROR_ABORT_SCAN_FAILED = "The Stop Scan task has failed. Error (0x{1:X}) {2}. Unable to stop the scan running by the process ID {0}. Log on to the computer and confirm that the FEP2010 client is installed and operating properly."
Const TASK_ERROR_APPLY_SETTINGS = "The task has failed to change settings. Error 0x{0:x}. Log on to the computer and confirm that the FEP2010 client is installed and operating properly, and then change settings locally."
Const TASK_ERROR_NOT_LSA = "This task must be run using a Local System account."
Const TASK_ERROR_NOT_SUPPORTED = "This FEP2010 client version is not supported."
Const TASK_ERROR_OPERATION_FAILED = "The task has failed. Error 0x{0:x}."
Const TASK_ERROR_SCAN_ABORTED = "The scan was stopped."
Const TASK_ERROR_SCAN_FAILED = "The Scan task has failed. Error 0x{0:X}. Log on to the computer and confirm that the FEP2010 client is installed and operating properly, and then launch a scan locally."
Const TASK_ERROR_SCAN_IN_PROGRESS = "A scan is already in progress."
Const TASK_ERROR_START_SERVICE = "The Enable Real-time Protection task has failed. Log on to the computer and confirm that the FEP2010 client is installed and operating properly, and then start the service locally."
Const TASK_ERROR_UPDATE_ERROR = "The Update Antimalware Definitions task has failed. Error 0x{0:X}. Log on to the computer and attempt to run the update locally. If updates fail, verify that WSUS is running and that the client computer has connectivity to Windows Update."
Const TASK_ERROR_UPDATE_ERROR_FOR_OPTION = "The Update Antimalware Definitions task with option {0} has failed. Error 0x{1:X}."
Const TASK_WARNING_ABORT_SCAN_NO_SCAN = "There is no scan in progress."
Const WIN32OS_WMI_QUERY = "select * from Win32_OperatingSystem"
Const WIN32PROCSTUP_WMICLASS_PROVIDERNAME = "Win32_ProcessStartup"
Const WIN32PROC_BYID_WMI_QUERY = "Select * from Win32_Process Where ID = {0}"
Const WIN32PROC_BYNAME_WMI_QUERY = "Select * from Win32_Process Where Name = '{0}'"
Const WIN32PROC_WMICLASS_PROVIDERNAME = "Win32_Process"
Const WIN32PROC_WMI_NAMESPACE = "winmgmts:{impersonationLevel=impersonate}!\\.\root\cimv2"
Const WIN32SERV_BYNAME_WMI_QUERY = "Select * from Win32_Service Where Name = '{0}'"

Dim g_strAMRegKey
Dim g_strClientInstallationRegKey
Dim g_strClientRootRegKey
Dim g_strAMPolicyRegKey
Dim g_strAMRegValue
Dim g_strAMScanTool
Dim g_strCSPTool
Dim g_strClientSupportDirPath
Dim g_strClientXPSupportDirPath

' This is the minimum version for Tasks
const C_MinVersionSupported = "2.0.457.0"

g_strAMRegKey = AM_REGKEY_ROOT
g_strClientRootRegKey = CLIENT_REGKEY_ROOT
g_strAMPolicyRegKey = AM_POLICY_REGKEY_ROOT
g_strAMScanTool = AM_REGVALUE_CLIENT_MPCMDRUN
g_strClientInstallationRegKey = AM_REGKEY_CLIENT_INSTKEY
g_strAMRegValue = AM_REGVALUE_CLIENT_INSTLOCATION
g_strCSPTool = AM_REGVALUE_CLIENT_CONFIGPOLICY
g_strClientSupportDirPath = FEP_SUPPRT_DIR_PATH
g_strClientXPSupportDirPath = FEP_SUPPRT_XP_DIR_PATH


Function UTCTimeToDate(strDateTime)
Dim objDate, iDateSepInd, iSecTermInd
Dim strDate, strTime

On Error Resume Next

iDateSepInd = InStr(strDateTime, "T")
iSecTermInd = InStr(strDateTime, ".")

If iDateSepInd = 0 Or iSecTermInd = 0 Then
UTCTimeToDate = Null
Exit Function
End If

strDate = Left(strDateTime, iDateSepInd - 1)
strTime = Mid(strDateTime, iDateSepInd + 1, iSecTermInd - iDateSepInd - 1)
UTCTimeToDate = CDate(strDate + " " + strTime)

If Err.Number &lt;&gt; 0 Then
g_objLog.WriteLog "UTCTimeToDate", LOG_ERROR, "Wrong format of data"
UTCTimeToDate = Null
Exit Function
Err.Clear
End If

End Function


Function CommonClientTimeToDate(strDateTime)
Dim objDate, strTmpDate

' Format of the input string: "20100429" meaning 29/04/2010

On Error Resume Next

If IsNull(strDateTime) or IsEmpty(strDateTime) Then
strDateTime = ""
End If

If Len(strDateTime) &lt;&gt; 8 Then
CommonClientTimeToDate = Null
Exit Function
End If


' Check that this is a valid date
strTmpDate = Left(strDateTime, 6) + "-" + Right(strDateTime, 2)
strTmpDate = Left(strTmpDate, 4) + "-" + Right(strTmpDate, 5)
objDate = CDate(strTmpDate)

If Err.Number &lt;&gt; 0 Then
g_objLog.WriteLog "CommonClientTimeToDate", LOG_ERROR, "Wrong format of data"
CommonClientTimeToDate = Null
Exit Function
Err.Clear
End If

' Get the date right
CommonClientTimeToDate = Right(strDateTime, 2) + "/" + Mid(strDateTime, 5, 2) + "/" + Left(strDateTime, 4)

End Function

Function IsError(value)
If Err.Number &lt;&gt; 0 Or TypeName(value) = "Nothing" Or TypeName(value) = "Null" Then
IsError = True
Else
IsError = False
End If
End Function

Function IsOS64Bit()
Dim strOSArchitecture

strOSArchitecture = GetOSArchitecture()
If Not IsNull(strOSArchitecture) Then
If InStr(strOSArchitecture, "64") &lt;&gt; 0 Then
IsOS64Bit = True
Else
IsOS64Bit = False
End If
Else
IsOS64Bit = Null
End If

End Function

Function IsStringHollow(strVal)
If Not IsNull(strVal) and (strVal &lt;&gt; "") and Not IsEmpty (strVal) and (strVal &lt;&gt; "-1") Then
IsStringHollow = false
Else
IsStringHollow = true
End If
End Function


Function GetValidStringValue(strVal)

' Empty string is not accepted by SCOM as part of the discovery, it will throw away the entire discovery and nothing will be shown in SCOM.
' If we won't fill out at all the fields we do not have a value for them, SCOM will keep the old discovered value which will cause wrong information to be shown in the UI.
' Only possibility is to fill out a white space to "delete" the old value by an empty space.

If Not IsStringHollow(strVal) Then
GetValidStringValue = strVal
Else
GetValidStringValue = " "
End If

End Function

Function GetValidDateString(dateVal)

If Not IsNull(dateVal) And TypeName(dateVal) = "Date" Then
GetValidDateString = CStr(dateVal)
Else
GetValidDateString = " "
End If

End Function

Function GetValidNumberValue(nValue, nDefault)
If IsNull(nValue) Or Not IsNumeric(nValue) Or Len(nValue) = 0 Then
GetValidNumberValue = nDefault
Else
GetValidNumberValue = CInt(nValue)
End If
End Function

Function GetOSArchitecture()
Dim strArchitecture

strArchitecture = g_objRegistry.ReadValue("HKEY_LOCAL_MACHINE", OS_REGKEY_ARCHITECTURE, OS_REGVALUE_ARCHITECTURE, "String", False)
If IsNull(strArchitecture) Then
g_objLog.WriteLog "GetOSArchitecture", LOG_FATALERROR, "Cannot retrieve OS architecture"
End If

GetOSArchitecture = strArchitecture

End Function

Class OSInfo
Public m_strName
Public m_strVersion
Public m_strServicePack
Public m_iProductType ' 1- Desktop, 2 - DC, 3 - Server
Public m_strBuildNumber
End Class

Function GetWindowsInfo()
On Error Resume Next

Dim strComputername, objWMIService, objQrySetting, objOS, objOSInfo

strComputername = "." ' Local computer
Set objWMIService = GetObject("winmgmts:{impersonationLevel=impersonate}!\\" &amp; strComputername &amp; "\root\cimv2")
If Err.Number &lt;&gt; 0 Then
Set GetWindowsInfo = Null
g_objLog.WriteLog "GetWindowsInfo", LOG_ERROR, "Cannot create WMI error=" + CStr(Err.Number)
Err.Clear
Exit Function
End If

Set objQrySetting = objWMIService.ExecQuery(WIN32OS_WMI_QUERY)
If Not IsObject(objQrySetting) Then
Set GetWindowsInfo = Null
g_objLog.WriteLog "GetWindowsInfo", LOG_ERROR, "Error query execution:" + CStr(Err.Number)
Err.Clear
Exit Function
End If

Set objOSInfo = new OSInfo
For Each objOS In objQrySetting
If Not IsObject(objOS) Then
Set GetWindowsInfo = Null
g_objLog.WriteLog "GetWindowsInfo", LOG_ERROR, "Error query execution:" + CStr(Err.Number)
Err.Clear
Exit Function
End If

objOSInfo.m_strName = objOS.Name
objOSInfo.m_strVersion = objOS.Version
objOSInfo.m_strServicePack = objOS.ServicePackMajorVersion
objOSInfo.m_iProductType = objOS.ProductType
objOSInfo.m_strBuildNumber = objOS.BuildNumber
Next

g_objLog.WriteLog "GetWindowsInfo:", LOG_INFO, FormatString5("Name = {0} Version = {1} ServicePack = {2} ProductType = {3} BuildNumber = {4}",_
objOSInfo.m_strName, objOSInfo.m_strVersion, objOSInfo.m_strServicePack, objOSInfo.m_iProductType, objOSInfo.m_strBuildNumber)

Set GetWindowsInfo = objOSInfo

Set objWMIService = Nothing
Set objQrySetting = Nothing
Set objOS = Nothing
End Function

const Windows_XP = "XP"
const Windows_Vista = "Vista"
const Windows_Windows7 = "Windows7"
const Windows_2003 = "Server_2003"
const Windows_2008 = "Server_2008"
const Windows_2008R2 = "Server_2008_R2"

Function GetOS(objOSInfo)
On Error Resume Next

If Not IsObject(objOSInfo) Then
GetOS = Null
g_objLog.WriteLog "GetOS", LOG_ERROR, "invalid object:" + CStr(Err.Number)
Err.Clear
Exit Function
End If

Dim verArray, osMajorVersion
verArray = Split(objOSInfo.m_strVersion, ".", -1, 1)
osMajorVersion = verArray(0) + "." + verArray(1)
If (objOSInfo.m_iProductType = "3") Then
' 3 is server OS
If (osMajorVersion = "6.1") Then
GetOS = Windows_2008R2
ElseIf (osMajorVersion = "6.0") Then
GetOS = Windows_2008
ElseIf (osMajorVersion = "5.2") Then
GetOS = Windows_2003
Else
GetOS = Null
End If
ElseIf (objOSInfo.m_iProductType = "1") Then
' 1 is desktop OS
If (osMajorVersion = "6.1") Then
GetOS = Windows_Windows7
ElseIf (osMajorVersion = "6.0") Then
GetOS = Windows_Vista
ElseIf ((osMajorVersion = "5.1") or (osMajorVersion = "5.2")) Then
GetOS = Windows_XP
Else
GetOS = Null
End If
Else
GetOS = Null
End If

End Function

const HKEY_CLASSES_ROOT = &amp;H80000000
const HKEY_CURRENT_USER = &amp;H80000001
const HKEY_LOCAL_MACHINE = &amp;H80000002
const HKEY_USERS = &amp;H80000003
const HKEY_CURRENT_CONFIG = &amp;H80000005

const REG_SZ = 1
const REG_EXPAND_SZ = 2
const REG_BINARY = 3
const REG_DWORD = 4
const REG_MULTI_SZ = 7

Class CRegistry

Public m_bIs64Bit

Private Function CreateWMIRegProvider(bIs64Bit)
Dim objReg, objCtx, objLocator, objServices

On Error Resume Next
Err.Clear

Set objCtx = CreateObject("WbemScripting.SWbemNamedValueSet")
If Err.Number &lt;&gt; 0 Then
g_objLog.WriteLog "CreateWMIRegProvider", LOG_ERROR, "Cannot create object WbemScripting.SWbemNamedValueSet, error=" + CStr(Err.Number)
CreateWMIRegProvider = Null
Err.Clear
Exit Function
End If

If bIs64Bit Then
objCtx.Add "__ProviderArchitecture", 64
Else
objCtx.Add "__ProviderArchitecture", 32
End If

Set objLocator = CreateObject("Wbemscripting.SWbemLocator")
If Err.Number &lt;&gt; 0 Then
g_objLog.WriteLog "CreateWMIRegProvider", LOG_ERROR, "Cannot create object WbemScripting.SWbemLocator, error=" + CStr(Err.Number)
CreateWMIRegProvider = Null
Err.Clear
Exit Function
End If

Set objServices = objLocator.ConnectServer("", REG_WMI_NAMESPACE,"","",,,,objCtx)
Set objReg = objServices.Get(REG_WMICLASS_PROVIDERNAME)

If Err.Number = 0 Then
Set CreateWMIRegProvider = objReg
Else
g_objLog.WriteLog "CreateWMIRegProvider", LOG_ERROR, "Cannot create WMI registry provider, error=" + CStr(Err.Number)
Set CreateWMIRegProvider = Null
Err.Clear
End If

End Function

Private Function DecodeHive(strHive)
Dim lHive

If strHive = "HKEY_CLASSES_ROOT" Then
lHive = HKEY_CLASSES_ROOT
ElseIf strHive = "HKEY_CURRENT_USER" Then
lHive = HKEY_CURRENT_USER
ElseIf strHive = "HKEY_LOCAL_MACHINE" Then
lHive = HKEY_LOCAL_MACHINE
ElseIf strHive = "HKEY_USERS" Then
lHive = HKEY_USERS
ElseIf strHive = "HKEY_CURRENT_CONFIG" Then
lHive = HKEY_CURRENT_CONFIG
Else
g_objLog.WriteLog "DecodeHive", LOG_ERROR, "Can't decode hive value " + strHive
lHive = Null
End If

DecodeHive = lHive
End Function

Private Function ReadEnumRegistryValue(strHive, strKey, strValueType, bIs64Bit)
Dim objReg, lHive, iValue, strWholeValue, strValue, strValueName, dwValue, abValue(), astrValue(), arrValueNames, arrValueTypes, i
Const C_Delimiter = ";"
On Error Resume Next
Err.Clear

lHive = DecodeHive(strHive)
If IsNull(lHive) Then
ReadEnumRegistryValue = Null
Exit Function
End If

Set objReg = CreateWMIRegProvider(bIs64Bit)
If IsNull(objReg) Then
ReadEnumRegistryValue = Null
Exit Function
End If

strWholeValue = ""
objReg.EnumValues lHive, strKey, arrValueNames, arrValueTypes
If Err.Number &lt;&gt; 0 Then
g_objLog.WriteLog "ReadEnumRegistryValue", LOG_ERROR, "Cannot enumerate registry key: " + strKey
ReadEnumRegistryValue = Null
Err.Clear
Exit Function
End If
If IsNull(arrValueNames) Or IsNull(arrValueTypes) Then
ReadEnumRegistryValue = strWholeValue
Exit Function
End If

For i=0 To UBound(arrValueNames)
strValueName = arrValueNames(i)
If strValueType = "*" Then
AddToDelimitedString strWholeValue, strValueName, C_Delimiter
Else
Select Case arrValueTypes(i)
Case REG_SZ
If strValueType = "String" Then
objReg.GetStringValue lHive,strKey,strValueName,strValue
If Err.Number &lt;&gt; 0 Then
g_objLog.WriteLog "ReadEnumRegistryValue", LOG_ERROR, "Cannot read registry key: " + strKey + ", value name: " + strValueName + ", type: " + strValueType
ReadEnumRegistryValue = Null
Err.Clear
Exit Function
End If
AddToDelimitedString strWholeValue, strValueName, C_Delimiter
End If
Case REG_DWORD
If strValueType = "DWORD" Then
objReg.GetDWORDValue lHive,strKey,strValueName,strValue
If Err.Number &lt;&gt; 0 Then
g_objLog.WriteLog "ReadEnumRegistryValue", LOG_ERROR, "Cannot read registry key: " + strKey + ", value name: " + strValueName + ", type: " + strValueType
ReadEnumRegistryValue = Null
Err.Clear
Exit Function
End If
AddToDelimitedString strWholeValue, strValueName, C_Delimiter
End If
End Select
End If
Next

ReadEnumRegistryValue = strWholeValue
End Function

Private Function ReadRegistryValue(strHive, strKey, strValueName, strValueType, bIs64Bit)
Dim objReg, lHive, strComputer, strValue, dwValue, abValue(), astrValue(), dwError

On Error Resume Next
Const ERROR_ACCESS_DENIED = 5 ' The only error code that will be translated as an error for logging
Err.Clear

If strValueName = "*" Then
ReadRegistryValue = ReadEnumRegistryValue(strHive, strKey, strValueType, bIs64Bit)
Exit Function
End If

lHive = DecodeHive(strHive)
If IsNull(lHive) Then
ReadRegistryValue = Null
Exit Function
End If

Set objReg = CreateWMIRegProvider(bIs64Bit)
If IsNull(objReg) Then
ReadRegistryValue = Null
Exit Function
End If
ReadRegistryValue = Null

If strValueType = "String" Then
dwError = objReg.GetStringValue( lHive,strKey,strValueName,strValue )
If dwError &lt;&gt; 0 Then
g_objLog.WriteLog "ReadRegistryValue", ConditionHelper(ERROR_ACCESS_DENIED=dwError, LOG_ERROR, LOG_INFO), FormatString4("Cannot read registry key: {0}, value name: {1}, type: {2}, error: {3}", strKey, strValueName, strValueType, dwError)
ReadRegistryValue = Null
Err.Clear
Exit Function
End If
ElseIf strValueType = "MultiString" Then
dwError = objReg.GetMultiStringValue( lHive,strKey,strValueName,astrValue )
If dwError &lt;&gt; 0 Then
g_objLog.WriteLog "ReadRegistryValue", ConditionHelper(ERROR_ACCESS_DENIED=dwError, LOG_ERROR, LOG_INFO), FormatString4("Cannot read registry key: {0}, value name: {1}, type: {2}, error: {3}", strKey, strValueName, strValueType, dwError)
ReadRegistryValue = Null
Err.Clear
Exit Function
End If
If Not IsNull(astrValue) Then
strValue = astrValue
Else
strValue = Null
End If
ElseIf strValueType = "ExpandedString" Then
dwError = objReg.GetExpandedStringValue( lHive,strKey,strValueName,strValue )
If dwError &lt;&gt; 0 Then
g_objLog.WriteLog "ReadRegistryValue", ConditionHelper(ERROR_ACCESS_DENIED=dwError, LOG_ERROR, LOG_INFO), FormatString4("Cannot read registry key: {0}, value name: {1}, type: {2}, error: {3}", strKey, strValueName, strValueType, dwError)
ReadRegistryValue = Null
Err.Clear
Exit Function
End If
ElseIf strValueType = "DWORD" Then
dwError = objReg.GetDWORDValue( lHive,strKey,strValueName,dwValue )
If dwError &lt;&gt; 0 Then
g_objLog.WriteLog "ReadRegistryValue", ConditionHelper(ERROR_ACCESS_DENIED=dwError, LOG_ERROR, LOG_INFO), FormatString4("Cannot read registry key: {0}, value name: {1}, type: {2}, error: {3}", strKey, strValueName, strValueType, dwError)
ReadRegistryValue = Null
Err.Clear
Exit Function
End If
If Not IsNull(dwValue) Then
strValue = CLng(dwValue)
Else
strValue = Null
End If
ElseIf strValueType = "QWORD" Then
dwError = objReg.GetQWORDValue( lHive,strKey,strValueName,dwValue )
If dwError &lt;&gt; 0 Then
g_objLog.WriteLog "ReadRegistryValue", ConditionHelper(ERROR_ACCESS_DENIED=dwError, LOG_ERROR, LOG_INFO), FormatString4("Cannot read registry key: {0}, value name: {1}, type: {2}, error: {3}", strKey, strValueName, strValueType, dwError)
ReadRegistryValue = Null
Err.Clear
Exit Function
End If
If Not IsNull(dwValue) Then
strValue = CStr(dwValue)
Else
strValue = Null
End If
ElseIf strValueType = "Binary" Then
dwError = objReg.GetBinaryValue( lHive,strKey,strValueName,abValue )
If dwError &lt;&gt; 0 Then
g_objLog.WriteLog "ReadRegistryValue", ConditionHelper(ERROR_ACCESS_DENIED=dwError, LOG_ERROR, LOG_INFO), FormatString4("Cannot read registry key: {0}, value name: {1}, type: {2}, error: {3}", strKey, strValueName, strValueType, dwError)
ReadRegistryValue = Null
Err.Clear
Exit Function
End If
If Not IsNull(abValue) Then
strValue = abValue
Else
strValue = Null
End If
Else
strValue = Null
End If

If Err.Number = 0 Then
ReadRegistryValue = strValue
Else
ReadRegistryValue = Null
Err.Clear
End If

End Function

Public Function ReadValue(strHive, strKey, strValueName, strValueType, bIs64Bit)
ReadValue = ReadRegistryValue(strHive, strKey, strValueName, strValueType,bIs64Bit)
End Function

Public Sub WriteValue(strHive, strKey, strValueName, strValueData, strValueType, bIs64Bit)
Dim objReg, lHive
Set objReg = CreateWMIRegProvider(bIs64Bit)

lHive = DecodeHive(strHive)
If IsNull(lHive) Then
g_objLog.WriteLog "WriteValue", LOG_ERROR, "Cannot decode a hive name: " + strHive
Exit Sub
End If

If strValueType = "String" Then
objReg.SetStringValue lHive,strKey,strValueName,strValueData
If Err.Number &lt;&gt; 0 Then
g_objLog.WriteLog "WriteValue", LOG_ERROR, "Cannot write registry key: " + strKey + ", value name: " + strValueName + ", type: " + strValueType
Exit Sub
End If
ElseIf strValueType = "DWORD" Then
objReg.SetDWORDValue lHive,strKey,strValueName,strValueData
If Err.Number &lt;&gt; 0 Then
g_objLog.WriteLog "WriteValue", LOG_ERROR, "Cannot write registry key: " + strKey + ", value name: " + strValueName + ", type: " + strValueType
Exit Sub
End If
Else
Err.Raise 87, "CRegistry", "Unsupported type: " + strValueType, "", ""
End If
End Sub


Function DeleteValue(strHive, strKey, strValueName, bIs64Bit)
Dim objReg, lHive
Set objReg = CreateWMIRegProvider(bIs64Bit)

lHive = DecodeHive(strHive)
If IsNull(lHive) Then
g_objLog.WriteLog "DeleteValue", LOG_ERROR, "Cannot decode a hive name: " + strHive
DeleteValue = 87 ' Invalid parameter
Exit Function
End If

DeleteValue = objReg.DeleteValue(lHive,strKey,strValueName)
End Function
End Class


Const LOG_SUCCESS = 0
Const LOG_ERROR = 1
Const LOG_FATALERROR = 2
Const LOG_WARNING = 4
Const LOG_INFO = 8
Const LOG_DEBUG = 16

Class CLog

Private m_iLogLevel
Private m_iMaxLogSize
Private m_iEffortCount
Private m_objFSO
Private m_strFName
Private m_bEnabled
Private m_strMessageBuffer
Private m_objAPI
Private m_bAPIEnabled
Private m_bIsFatalErrorIssued
Private m_strLogLocation

Public Function Init(strFName)
On Error Resume Next
Dim strRootRegKey, strLogLevelValueName, strLogLevel, iEnabled, objLogFile

strRootRegKey = LOG_REGKEY
strLogLevelValueName = "Debug"
m_iEffortCount = 20
m_strMessageBuffer = ""
m_bIsFatalErrorIssued = False

m_bEnabled = False

iEnabled = g_objRegistry.ReadValue("HKEY_LOCAL_MACHINE", strRootRegKey, LOG_REGVALUE_ENABLED, "DWORD", g_bIs64Bit)
If Not IsNull(iEnabled) Then
If iEnabled = 1 Then
m_bEnabled = True
End If
End If

m_iMaxLogSize = g_objRegistry.ReadValue("HKEY_LOCAL_MACHINE", strRootRegKey, "max_size", "DWORD", g_bIs64Bit)
If IsNull(m_iMaxLogSize) Then
m_iMaxLogSize = 1000000
Else
m_iMaxLogSize = m_iMaxLogSize
End If

If m_bEnabled = True Then
InitializeScriptingAPI()
Set m_objFSO = CreateObject("Scripting.FileSystemObject")
If Err.Number &lt;&gt; 0 Then
g_objLog.WriteLog "CLog.Init", LOG_ERROR, "Cannot initialize"
Init = False
Err.Clear
Exit Function
End If

m_strLogLocation = m_objFSO.BuildPath(m_objFSO.GetSpecialFolder(2), LOG_SUBFOLDER_NAME)
m_strFName = m_objFSO.BuildPath(m_strLogLocation, strFName)

If m_objFSO.FileExists(m_strFName) Then
Set objLogFile = m_objFSO.GetFile(m_strFName)
If Err.Number &lt;&gt; 0 Then
g_objLog.WriteLog "CLog.Init", LOG_ERROR, "Cannot get log file"
Init = False
Err.Clear
Exit Function
End If
If objLogFile.Size &gt; m_iMaxLogSize Then
m_objFSO.DeleteFile m_strFName
End If

If Err.Number &lt;&gt; 0 Then
g_objLog.WriteLog "CLog.Init", LOG_ERROR, "Cannot delete file"
Init = False
Err.Clear
Exit Function
End If
End If
End If

Init = True

WriteLog "CLog.Init", LOG_INFO, "Initialized successfully"

End Function

Function InitializeScriptingAPI()
On Error Resume Next
Err.Clear

Set m_objAPI = CreateObject("MOM.ScriptAPI")
If Err.Number = 0 Then
m_bAPIEnabled = True
Else
Err.Clear
m_bAPIEnabled = False
End If
End Function

Public Function IsFatalErrorIssued()
IsFatalErrorIssued = m_bIsFatalErrorIssued
End Function

Public Sub WriteLog(strFuncName, iSeverity, strMessage)
Dim objShell, strFmtMessage, strErrSeverityMessage, iLogSeverity, strEntityMsg
Dim iEffort, strTime

On Error Resume Next
Err.Clear

If m_bEnabled = False Then
Exit Sub
End If

Const Error_event = 1
Const Warning_event = 2
Const Information_event = 0

If iSeverity = LOG_SUCCESS Then
strErrSeverityMessage = "SUCCESS"
iLogSeverity = Information_event
ElseIf iSeverity = LOG_ERROR Then
strErrSeverityMessage = "ERROR"
iLogSeverity = Error_event
ElseIf iSeverity = LOG_INFO Then
strErrSeverityMessage = "INFO"
iLogSeverity = Information_event
ElseIf iSeverity = LOG_FATALERROR Then
strErrSeverityMessage = "FATAL ERROR"
m_bIsFatalErrorIssued = True
iLogSeverity = Error_event
ElseIf iSeverity = LOG_DEBUG Then
strErrSeverityMessage = "DEBUG"
iLogSeverity = Information_event
Else
Exit Sub
End If

If m_bEnabled = True Then
strTime = CStr(Date) + " " + CStr(Hour(Now)) + ":" + CStr(Minute(Now)) + "." + CStr(Second(Now))
strFmtMessage = strTime + " " + strErrSeverityMessage + " " + strFuncName + ":" + strMessage
m_strMessageBuffer = m_strMessageBuffer + strFmtMessage + vbCrLf

If m_bAPIEnabled Then 'Write to ops manager log as well
m_objAPI.LogScriptEvent "Forefront Endpoint Protection", 1000, iLogSeverity, strFmtMessage
End If
End If

End Sub

Public Function SaveLogToDisk()
On Error Resume Next
Dim objTextFile
Dim iEffort

If m_bEnabled = False Then
Exit Function
End If

SaveLogToDisk = False
For iEffort = 0 To m_iEffortCount
If Not m_objFSO.FolderExists(m_strLogLocation) Then
m_objFSO.CreateFolder m_strLogLocation
End If
Err.Clear
Set objTextFile = m_objFSO.OpenTextFile (m_strFName, 8, True, 0)
If Err.Number = 0 Then
objTextFile.WriteLine(m_strMessageBuffer)
objTextFile.Close

If Err.Number = 0 Then
SaveLogToDisk = True
Exit For
End If
End If
Next

End Function

End Class




Const SW_HIDE = 0

Class CWmiProcess
Private m_bIsInitialized
Private m_objWMIService

Public Sub Class_Initialize
m_bIsInitialized = False

Set m_objWMIService = GetObject(WIN32PROC_WMI_NAMESPACE)
If Err.Number &lt;&gt; 0 Then
g_objLog.WriteLog "CWmiProcess::Class_Initialize", LOG_ERROR, "Cannot create object WScript.Shell, error=" + CStr(Err.Number)
Err.Clear
Exit Sub
End If

m_bIsInitialized = True
End Sub

Public Function Execute(strCmdLine, bWaitExit, dwTimeout)
Const WBEM_S_TIMEDOUT = &amp;H40004
Const WBEM_PROCESS_CREATE_INVALID_PARAMETER = 21
Dim strProcessName, dwExitCode, objProcess, objStartup, objConfig, intProcessID

On Error Resume Next
Err.Clear

If Not m_bIsInitialized Then
Execute = WBEM_PROCESS_CREATE_INVALID_PARAMETER
Exit Function
End If

Set objStartup = m_objWMIService.Get(WIN32PROCSTUP_WMICLASS_PROVIDERNAME)
Set objConfig = objStartup.SpawnInstance_
objConfig.ShowWindow = SW_HIDE

Set objProcess = m_objWMIService.Get("Win32_Process")
Execute = objProcess.Create(strCmdLine, Null, objConfig, intProcessID)
If Execute &lt;&gt; 0 Then
g_objLog.WriteLog "CWmiProcess::Execute", LOG_ERROR, "Cannot create process, error=" + Execute
Err.Clear
Exit Function
End If

If Not bWaitExit Then
Exit Function
End If

Do While DoesProcessRunByID(intProcessID) And dwTimeout &gt; 0
WScript.Sleep 1
dwTimeout = dwTimeout - 1
Loop

If DoesProcessRunByID(intProcessID) Then
g_objLog.WriteLog "CWmiProcess::Execute", LOG_ERROR, "TimeOut exceeded"
Execute = WBEM_S_TIMEDOUT ' Play with WMI's agenda
Err.Clear
Exit Function
End If

End Function


Public Function GetProcess(strProcessName)
Dim objProcess, objcolProcess

On Error Resume Next
Err.Clear

If Not m_bIsInitialized Then
Set GetProcess = Nothing
Exit Function
End If

Set objcolProcess = m_objWMIService.ExecQuery (FormatString1(WIN32PROC_BYNAME_WMI_QUERY, strProcessName))
Set GetProcess = objcolProcess
If Err.Number &lt;&gt; 0 Then
g_objLog.WriteLog "CWmiProcess::GetProcess", LOG_ERROR, "Cannot enumerate processes, error=" + CStr(Err.Number)
Err.Clear
Exit Function
End If
End Function

Public Function GetProcessByID(intProcessID)
Dim objProcess, objcolProcess

On Error Resume Next
Err.Clear

If Not m_bIsInitialized Then
Set GetProcessByID = Nothing
Exit Function
End If

Set objcolProcess = m_objWMIService.ExecQuery _
(WIN32PROC_BYID_WMI_QUERY, CStr(intProcessID))
Set GetProcessByID = objcolProcess
If Err.Number &lt;&gt; 0 Then
g_objLog.WriteLog "CWmiProcess::GetProcessByID", LOG_ERROR, "Cannot enumerate processes, error=" + CStr(Err.Number)
Err.Clear
Exit Function
End If
End Function

Public Function DoesProcessRunByID(intProcessID)
On Error Resume Next
Err.Clear

Dim objProcess, objcolProcess

If Not m_bIsInitialized Then
DoesProcessRunByID = False
Exit Function
End If

Set objcolProcess = GetProcessByID(intProcessID)
If IsError(objcolProcess) Then
DoesProcessRunByID = False
Exit Function
End If

For Each objProcess In objcolProcess
DoesProcessRunByID = True
Next

If Err.Number &lt;&gt; 0 Then
g_objLog.WriteLog "CWmiProcess::DoesProcessRunByID", LOG_ERROR, "DoesProcessRunByID failed, error=" + CStr(Err.Number)
DoesProcessRunByID = False
Err.Clear
End If

End Function

Public Function KillProcess(strProcessName)
On Error Resume Next
Dim objProcess, objcolProcess

If Not m_bIsInitialized Then
KillProcess = False
Exit Function
End If

Set objcolProcess = GetProcess(strProcessName)
If IsError(objcolProcess) Then
g_objLog.WriteLog "CWmiProcess::DoesProcessRun", LOG_WARNING, "processes doesn't run:" + strProcessName
KillProcess = False
Exit Function
End If

For Each objProcess In objcolProcess
objProcess.Terminate()
Next
If Err.Number &lt;&gt; 0 Then
g_objLog.WriteLog "CWmiProcess::KillProcess", LOG_ERROR, "KillProcess failed, error=" + CStr(Err.Number)
KillProcess = False
Err.Clear
Exit Function
End If

KillProcess = True
End Function


End Class

' Partial simulation of String.Format method
' Supports {n}, {n:x} and {n:X} where n is a place holder for the paramter position number
Function FormatString1(strFormat, param1)
FormatString1 = FormatString(strFormat, Array(param1))
End Function

Function FormatString2(strFormat, param1, param2)
FormatString2 = FormatString(strFormat, Array(param1, param2))
End Function

Function FormatString3(strFormat, param1, param2, param3)
FormatString3 = FormatString(strFormat, Array(param1, param2, param3))
End Function

Function FormatString4(strFormat, param1, param2, param3, param4)
FormatString4 = FormatString(strFormat, Array(param1, param2, param3, param4))
End Function

Function FormatString5(strFormat, param1, param2, param3, param4, param5)
FormatString5 = FormatString(strFormat, Array(param1, param2, param3, param4, param5))
End Function

' Most generic version which accepts Array
Function FormatString(strFormat, arrayParams)
Dim param, i
FormatString = strFormat
i = 0
For Each param in arrayParams
Dim paramToOutput
If IsNull(param) Then
paramToOutput = "null"
Else
paramToOutput = param
End If
If TypeName(param)="Byte" Or TypeName(param)="Integer" Or TypeName(param)="Long" Or TypeName(param)="Decimal" Then
' Try x formating
FormatString = Replace(FormatString, "{" &amp; CStr(i) &amp; ":x}", LCase(Hex(paramToOutput)), 1, -1, vbBinaryCompare)
' Try X formating (Hex returns upper case string by default)
FormatString = Replace(FormatString, "{" &amp; CStr(i) &amp; ":X}", Hex(paramToOutput), 1, -1, vbBinaryCompare)
End If
FormatString = Replace(FormatString, "{" &amp; CStr(i) &amp; "}", CStr(paramToOutput), 1, -1, vbTextCompare)
i = i + 1
Next
End Function

Function IsVersionSupported(strMinVersion, strVersion)
Dim aMinVer, aVer, cMinVer, cVer, cMin, i

If strMinVersion = strVersion Then
IsVersionSupported = True
End If

If IsNull(strMinVersion) Or IsNull(strVersion) Or Len(strMinVersion)=0 Or Len(strVersion)=0 Then
IsVersionSupported = False
End If

aMinVer = Split(strMinVersion,".")
aVer = Split(strVersion,".")

cMinVer = UBound(aMinVer)
cVer = UBound(aVer)

If cVer&gt;cMinVer Then
cMin = cMinVer
Else
cMin = cVer
End If

For i=0 To cMin
If aMinVer(i)&lt;aVer(i) Then
Exit For
End If
If aMinVer(i)&gt;aVer(i) Then
IsVersionSupported = False
Exit Function
End If
Next

If cVer&gt;=cMinVer Then
IsVersionSupported = True
Exit Function
End If

If cVer&lt;cMinVer Then
For i=cMin+1 To cMinVer
If aMinVer(i) &lt;&gt; 0 Then
IsVersionSupported = False
Exit Function
End If
Next
IsVersionSupported = True
Exit Function
End If

IsVersionSupported = False
End Function

Function ConditionHelper(cond, op1, op2)
If cond Then
ConditionHelper = op1
Else
ConditionHelper = op2
End If
End Function

Sub AddToDelimitedString(ByRef strDelimitedString, strNewValue, strDelimiter)
If Len(strDelimitedString) &gt; 0 Then
strDelimitedString = strDelimitedString &amp; strDelimiter
End If
strDelimitedString = strDelimitedString &amp; strNewValue
End Sub
'consts
Dim m_DOUBLE_QUOTE
Dim m_strCommentString
Dim m_REGEX_INI_SECTION_HEADER
Dim m_REGEX_INI_KEY_VALUE_LINE
Dim m_REGEX_TRAILING_COMMENT
Dim m_REGEX_WHITE_SPACE_PADDED_STRING
Dim m_REGEX_m_DOUBLE_QUOTED_STRING

m_DOUBLE_QUOTE = chr(34)
m_strCommentString = ";"
m_REGEX_INI_SECTION_HEADER = "^\s*(?!" &amp; m_strCommentString &amp; ")\s*\[\s*(.*[^\s*])\s*]\s*$"
m_REGEX_INI_KEY_VALUE_LINE = "^\s*(?!" &amp; m_strCommentString &amp; ")\s*" &amp; "([^=]*)" &amp; "\s*=\s*" &amp; "(.*)" &amp; "\s*$"
m_REGEX_TRAILING_COMMENT = "^\s*([^" &amp; m_strCommentString &amp; "]+[^\s*])(\s+" &amp; m_strCommentString &amp; ".*)$"
m_REGEX_WHITE_SPACE_PADDED_STRING = "^\s*(.*[^\s*])\s*$"
m_REGEX_m_DOUBLE_QUOTED_STRING = "^" &amp; m_DOUBLE_QUOTE &amp; ".*" &amp; m_DOUBLE_QUOTE &amp; "$"

'variables
Dim objINIFile
Dim strIniFileContents
Dim m_arrLines
Dim m_regEx
Dim m_bfileLoaded




Function RegExTest(strInputString, strPattern)
m_regEx.Pattern = strPattern
RegExTest = m_regEx.Test(strInputString)
End Function

Function RegExEscapeMetaCharacters(strInputString)
m_regEx.Global = True
m_regEx.Pattern = "([\$\(\)\*\+\.\[\?\\\^\{\|])"
RegExEscapeMetaCharacters = m_regEx.Replace(strInputString, "\$1")
m_regEx.Global = False
End Function

Private Function RegExReplace(strInputString, strPattern, strReplacementString)
m_regEx.Pattern = strPattern
RegExReplace = m_regEx.Replace(strInputString, strReplacementString)
End Function

Private Function GetRegExSubMatch(strInputString, strPattern, strSubMatchIndex)
Dim strSubMatch
Dim strNoTrailingComment
Dim strTrimmedLine
Dim strTrimDoubleQuote
strSubMatch = RegExReplace(strInputString, strPattern, strSubMatchIndex)
strNoTrailingComment = RegExReplace(strSubMatch, m_REGEX_TRAILING_COMMENT, "$1")
strTrimmedLine = RegExReplace(strNoTrailingComment, m_REGEX_WHITE_SPACE_PADDED_STRING, "$1")
If RegExTest(strTrimmedLine, m_REGEX_m_DOUBLE_QUOTED_STRING) Then
strTrimDoubleQuote = Mid(strTrimmedLine, 2, Len(strTrimmedLine) - 2)
GetRegExSubMatch = strTrimDoubleQuote
Else
GetRegExSubMatch = strTrimmedLine
End If
End Function

Private Function GetValue(strInputString)
GetValue = GetRegExSubMatch(strInputString, m_REGEX_INI_KEY_VALUE_LINE, "$2")
End Function

Function ReadValue(strSectionName, strKeyName)
Dim blnInSection
Dim i
Dim strLine
Dim strSectionNameEscaped
Dim strKeyNameEscaped
Dim strRegexSection
Dim strRegexKey

strSectionNameEscaped = RegExEscapeMetaCharacters(strSectionName)
strKeyNameEscaped = RegExEscapeMetaCharacters(strKeyName)

strRegexSection = "^\s*\[\s*" &amp; strSectionNameEscaped &amp; "\s*]"
strRegexKey = "^\s*" &amp; m_DOUBLE_QUOTE &amp; "?" &amp; strKeyNameEscaped &amp; m_DOUBLE_QUOTE &amp; "?" &amp; "\s*=\s*"



ReadValue = ""
If m_bfileLoaded Then
For i = 0 to Ubound(m_arrLines)
strLine = m_arrLines(i)
If RegExTest(strLine, strRegexSection) Then
blnInSection = True
ElseIf blnInSection Then
If RegExTest(strLine, m_REGEX_INI_SECTION_HEADER) Then
Exit For
Else
If RegExTest(strLine, strRegexKey) Then
ReadValue = GetValue(strLine)
Exit For
End If
End If
End If
Next
Else
Err.Raise 5002, , "No File Loaded"
End IF
End Function

Class CDeploymentStatusData

' Indicates the error of monitor's condition
Public m_iDeploymentErrorFound

' Indicates state of deployment according to FEP's setup error file
Public m_strDeploymentState

' Indicates more information of deployment according to FEP's setup error file
Public m_strDeploymentFailureMoreInfo

' Indicates the HRESULT of the error code in FEP's setup error file
Public m_strDeploymentErrorCode
End Class



Class CDeploymentStatusOperator
Private m_bIsInitialized
Private m_objFSO
Private m_objShell

Public Sub Class_Initialize
m_bIsInitialized = False

'Set file system object
Set m_objFSO = CreateObject("Scripting.FileSystemObject")
If Not IsObject(m_objFSO) Then
g_objLog.WriteLog "CDeploymentStatusOperator::Class_Initialize", LOG_ERROR, "Cannot create object Scripting.FileSystemObject, error=" + CStr(Err.Number)
Err.Clear
Exit Sub
End If

'Get WScript.Shell object to expand environment
Set m_objShell = WScript.CreateObject("WScript.Shell")
If Not IsObject(m_objShell) Then
g_objLog.WriteLog "CDeploymentStatusOperator::Class_Initialize", LOG_ERROR, "Cannot create object WScript.Shell, error=" + CStr(Err.Number)
Err.Clear
Exit Sub
End If

m_bIsInitialized = True
End Sub

Public Function GetData(strIsClientInstalled, objDeploymentStatusData)
Dim strFepSupportDir, strErrFilePath, objFile, strFileContent
Dim strHresult, strDescription, bFepSupportDirExist
On Error Resume Next

If Not m_bIsInitialized Then
g_objLog.WriteLog "CDeploymentStatusOperator.GetData", LOG_ERROR, "Quiting, object is not initialized"
GetData = False
Exit Function
End If

If IsNull(objDeploymentStatusData) Then
g_objLog.WriteLog "CDeploymentStatusOperator.GetData", LOG_ERROR, "Parameter objDeploymentStatusData is null, quiting."
GetData = False
Exit Function
End If

g_objLog.WriteLog "CDeploymentStatusOperator.GetData", LOG_INFO, "Started, IsClientInstalled=" &amp; strIsClientInstalled

' Check OS version for correct folder path
g_objLog.WriteLog "CDeploymentStatusOperator.GetData", LOG_INFO, "Checking OS information"

Dim objOSInfo

Set objOSInfo = GetWindowsInfo()

If Not IsObject(objOSInfo) Then
g_objLog.WriteLog "CDeploymentStatusOperator.GetData", LOG_INFO, "Cannot retrieve OS information"
GetData = False
Exit Function
End If

Dim strOSVersion
strOSVersion = GetOS(objOSInfo)
If strOSVersion &lt;&gt; Windows_2003 And strOSVersion &lt;&gt; Windows_XP Then
strFepSupportDir = m_objShell.ExpandEnvironmentStrings(g_strClientSupportDirPath)
Else
strFepSupportDir = m_objShell.ExpandEnvironmentStrings(g_strClientXPSupportDirPath)
End If

g_objLog.WriteLog "CDeploymentStatusOperator.GetData", LOG_INFO, "OS Version=" &amp; strOSVersion

bFepSupportDirExist = m_objFSO.FolderExists(strFepSupportDir)
g_objLog.WriteLog "CDeploymentStatusOperator.GetData", LOG_INFO, "Support folder exists (" &amp; strFepSupportDir &amp; ")? = " &amp; CStr(bFepSupportDirExist)
objDeploymentStatusData.m_iDeploymentErrorFound = DEPLOY_FAILED_MONITOR_HEALTHY

' It's not a real loop, it's just for quitting the function gracefully
Do
If strIsClientInstalled&lt;&gt;"True" And Not bFepSupportDirExist Then

' No client dir, no support dir - FEP wasn't installed here
objDeploymentStatusData.m_strDeploymentState = FEP_DEPLOY_STATUS_NO_INSTALL_DETECTED
Else
g_objLog.WriteLog "CDeploymentStatusOperator.GetData", LOG_INFO, "Checking in ProgramData folder for deployment error file, path: " &amp; strErrFilePath
strErrFilePath = strFepSupportDir &amp; "\" &amp; FEP_DEPLOY_ERROR_FILE_NAME

' The file might exist although IsClientInstalled="True", for example: reboot required
If m_objFSO.FileExists(strErrFilePath) Then
' File exists
g_objLog.WriteLog "CDeploymentStatusOperator.GetData", LOG_INFO, "Deployment Error File exists"

' Read file content
Const ForReading = 1
Const AsciiFormat = 0
Set objINIFile = m_objFSO.OpenTextFile(strErrFilePath, ForReading, False, AsciiFormat)

If Not IsObject(objINIFile) Then
g_objLog.WriteLog "CDeploymentStatusOperator.GetData", LOG_ERROR, "Couldn't open " + strErrFilePath + " for reading, quiting."
Exit Do
End If

strIniFileContents = objINIFile.ReadAll
m_arrLines = Split(strIniFileContents, vbCrLf)
objINIFile.Close
g_objLog.WriteLog "CDeploymentStatusOperator.GetData", LOG_INFO, "Deployment Error File content: " &amp; strIniFileContents

m_bfileLoaded = True

Set m_regEx = New RegExp
m_regEx.IgnoreCase = True
m_regEx.Global = False

strHresult = ReadValue("EppSetupResult", "HRESULT")

g_objLog.WriteLog "CDeploymentStatusOperator.GetData", LOG_INFO, "Deployment result: " &amp; strHresult


strDescription = ReadValue("EppSetupResult", "Description")

g_objLog.WriteLog "CDeploymentStatusOperator.GetData", LOG_INFO, "Deployment description: " &amp; strDescription

If strHresult = DEPLOY_FAILED_HRESULT_RESTART Or strHresult = DEPLOY_FAILED_HRESULT_RESTART2 Then ' It's a reboot required
objDeploymentStatusData.m_strDeploymentState = FEP_DEPLOY_STATUS_REBOOT_REQUIRED
ElseIf strHresult = DEPLOY_FAILED_HRESULT_CANCEL Then
objDeploymentStatusData.m_strDeploymentState = FEP_DEPLOY_STATUS_USER_CANCELED
ElseIf strHresult = DEPLOY_FAILED_HRESULT_SUCCESS Then
If strIsClientInstalled="True" Then
objDeploymentStatusData.m_strDeploymentState = FEP_DEPLOY_STATUS_INSTALLED
Else
objDeploymentStatusData.m_strDeploymentState = FEP_DEPLOY_STATUS_UNINSTALLED
End If
Else
objDeploymentStatusData.m_strDeploymentState = FEP_DEPLOY_STATUS_FAILED
' Consider as non-healthy state
objDeploymentStatusData.m_iDeploymentErrorFound = DEPLOY_FAILED_MONITOR_CRITICAL
End If

' Now, build the failure more info - if it's an error
objDeploymentStatusData.m_strDeploymentErrorCode = strHresult
objDeploymentStatusData.m_strDeploymentFailureMoreInfo = strDescription
Else
' File doesn't exist - FEP installed successfully or was uninstalled (no errors detected)
g_objLog.WriteLog "CDeploymentStatusOperator.GetData", LOG_INFO, "Deployment Error File does NOT exist, strIsClientInstalled=" &amp; strIsClientInstalled

If strIsClientInstalled="True" Then
objDeploymentStatusData.m_strDeploymentState = FEP_DEPLOY_STATUS_INSTALLED
Else
objDeploymentStatusData.m_strDeploymentState = FEP_DEPLOY_STATUS_UNINSTALLED
End If

End If
End If
Loop While (False)

g_objLog.WriteLog "CDeploymentStatusOperator.GetData", LOG_DEBUG, "m_strDeploymentState=" &amp; _
objDeploymentStatusData.m_strDeploymentState &amp; ", m_strDeploymentFailureMoreInfo=" &amp; _
objDeploymentStatusData.m_strDeploymentFailureMoreInfo &amp; ", m_iDeploymentErrorFound= " &amp;_
objDeploymentStatusData.m_iDeploymentErrorFound

If Err.Number = 0 Then
g_objLog.WriteLog "CDeploymentStatusOperator.GetData", LOG_INFO, "Finished successfully"
GetData = True
Else
g_objLog.WriteLog "CDeploymentStatusOperator.GetData", LOG_ERROR, "Cannot execute CDeploymentStatusOperator.GetData"
GetData = False
Err.Clear
Exit Function
End If
End Function
End Class

Class CServerCandidateDiscoveryData
Public m_strName
Public m_strProductVersion
Public m_strIsClientInstalled
Public m_strDeploymentState
Public m_strDeploymentStateMoreInfo
End Class

Class CServerCandidateWMIOperator

Public Function IsClientInstalled()
Dim objWMIService, strQuery, objColAntimalwareHealthStatus, objAntimalwareHealthStatus
Dim dwRTSDirection
On Error Resume Next

g_objLog.WriteLog "CServerCandidateWMIOperator.IsClientInstalled", LOG_INFO, "Started"

Set objWMIService = GetObject(AM_WMI_NAMESPACE)

If Not IsObject(objWMIService) Then
IsClientInstalled = "False"
g_objLog.WriteLog "CServerCandidateWMIOperator.IsClientInstalled", LOG_ERROR, "Error query execution:" + CStr(Err.Number)
Err.Clear
Exit Function
End If

strQuery = AM_WMI_HEALTH_STATUS_QUERY
Set objColAntimalwareHealthStatus = objWMIService.ExecQuery(strQuery,"WQL", 48)

If Not IsObject(objColAntimalwareHealthStatus) Then
IsClientInstalled = "False"
g_objLog.WriteLog "CServerCandidateWMIOperator.IsClientInstalled", LOG_ERROR, "Error query execution:" + CStr(Err.Number)
Err.Clear
Exit Function
End If

For Each objAntimalwareHealthStatus In objColAntimalwareHealthStatus
If Not IsObject(objAntimalwareHealthStatus) Then 'Means "Object not found"
IsClientInstalled = "False"
g_objLog.WriteLog "CServerCandidateWMIOperator.IsClientInstalled", LOG_ERROR, "Error query execution:" + CStr(Err.Number)
Err.Clear
Exit Function
End If
Next

If Err.Number = 0 Then
g_objLog.WriteLog "CServerCandidateWMIOperator.IsClientInstalled", LOG_INFO, "Finished successfully"
IsClientInstalled = "True"
Else
g_objLog.WriteLog "CServerCandidateWMIOperator.IsClientInstalled", LOG_ERROR, "FEP client is not installed on server"
IsClientInstalled = "False"
Err.Clear
Exit Function
End If

End Function
End Class

Class CServerCandidateRegOperator

Public Function GetData(objServerCandidateDiscoveryData)
Dim strValueKey, strValue, objServerCandidateWMIOperator, objDeploymentStatusOperator, objDeploymentStatusData
On Error Resume Next

g_objLog.WriteLog "CServerCandidateRegOperator.GetData", LOG_INFO, "Started"

strValueKey = g_strClientInstallationRegKey
strValue = g_objRegistry.ReadValue("HKEY_LOCAL_MACHINE", strValueKey, "*", "String", g_bIs64Bit)
If IsNull(strValue) Or IsEmpty(strValue) Or (strValue = "") Then
objServerCandidateDiscoveryData.m_strIsClientInstalled = "False"
Else
Set objServerCandidateWMIOperator = New CServerCandidateWMIOperator
objServerCandidateDiscoveryData.m_strIsClientInstalled = objServerCandidateWMIOperator.IsClientInstalled()
End If

strValueKey = g_strClientInstallationRegKey
strValue = g_objRegistry.ReadValue("HKEY_LOCAL_MACHINE", strValueKey, AM_REGVALUE_CLIENT_VERSION, "String", g_bIs64Bit)
objServerCandidateDiscoveryData.m_strProductVersion = GetValidStringValue(strValue)

Set objDeploymentStatusData = New CDeploymentStatusData
Set objDeploymentStatusOperator = New CDeploymentStatusOperator

If objDeploymentStatusOperator.GetData(objServerCandidateDiscoveryData.m_strIsClientInstalled, objDeploymentStatusData) Then
g_objLog.WriteLog "CServerCandidateRegOperator.GetData", LOG_INFO, "Deployment status data retrieved successfully"
Else
g_objLog.WriteLog "CServerCandidateRegOperator.GetData", LOG_ERROR, "Cannot retrieve deployment status data"
End If

If Not IsNull(objDeploymentStatusData) Then
' Try to return whatever we have
objServerCandidateDiscoveryData.m_strDeploymentState = GetValidStringValue(objDeploymentStatusData.m_strDeploymentState)
objServerCandidateDiscoveryData.m_strDeploymentStateMoreInfo = GetValidStringValue(objDeploymentStatusData.m_strDeploymentFailureMoreInfo)
End If

If objServerCandidateDiscoveryData.m_strIsClientInstalled = "False" Then
objServerCandidateDiscoveryData.m_strProductVersion = GetValidStringValue("")
End If

If Err.Number = 0 Then
g_objLog.WriteLog "CServerCandidateRegOperator.GetData", LOG_INFO, "Finished successfully"
GetData = True
Else
GetData = False
g_objLog.WriteLog "CServerCandidateRegOperator.GetData", LOG_ERROR, "Cannot execute CServerCandidateRegOperator.GetData"
Err.Clear
Exit Function
End If
End Function
End Class

Function CreateProtectedServerCandidate(bIsValid)
On Error Resume Next
Err.Clear

Dim g_objAPI
Set g_objAPI = CreateObject("MOM.ScriptAPI")

If Err.Number &lt;&gt; 0 Then
g_objLog.WriteLog "Microsoft.FEP.ProtectedServerCandidate.DS.vbs", LOG_ERROR, "Cannot create MOM.ScriptAPI object, error:" + CStr(Err.Number)
Err.Clear
CreateProtectedServerCandidate = False
Exit Function
End If

CreateProtectedServerCandidate = True

g_objLog.WriteLog "Microsoft.FEP.ProtectedServerCandidate.DS.vbs", LOG_INFO, "AM start: SourceId = " &amp; g_SourceID &amp; " ManagedEntityId = " &amp; g_ManagedEntityId &amp; " ServerId = " &amp; g_ServerId

set g_oDiscoveryData = g_objAPI.CreateDiscoveryData(0, g_SourceID, g_ManagedEntityId)
If Err.Number &lt;&gt; 0 Then
g_objLog.WriteLog "Microsoft.FEP.ProtectedServer.DS.vbs", LOG_ERROR, "Cannot create discovery data, error:" + CStr(Err.Number)
Err.Clear
CreateProtectedServerCandidate = False
Exit Function
End If

If Not bIsValid Then
Call g_objAPI.Return(g_oDiscoveryData) ' The discovery should create an empty discovery data to avoid SCOM errors
If Err.Number &lt;&gt; 0 Then
g_objLog.WriteLog "Microsoft.FEP.ProtectedServerCandidate.DS.vbs", LOG_ERROR, "Error submitting discovery data, error:" + CStr(Err.Number)
Err.Clear
CreateProtectedServerCandidate = False
End If
Exit Function
End If

' fill out properties of the AM discovered object
Set g_oInst = g_oDiscoveryData.CreateClassInstance("$MPElement[Name='Microsoft.FEP.ProtectedServerCandidate']$")
Call g_oInst.AddProperty("$MPElement[Name='Windows!Microsoft.Windows.Computer']/PrincipalName$", g_ServerId)
Call g_oInst.AddProperty("$MPElement[Name='Microsoft.FEP.ProtectedServerCandidate']/ServerId$", g_ServerId)

g_objLog.WriteLog "Microsoft.FEP.ProtectedServerCandidate.DS.vbs", LOG_INFO, " g_objProtectedServerCandidateDiscoveryData.m_strIsClientInstalled = " &amp; g_objProtectedServerCandidateDiscoveryData.m_strIsClientInstalled
Call g_oInst.AddProperty("$MPElement[Name='Microsoft.FEP.ProtectedServerCandidate']/IsClientInstalled$", g_objProtectedServerCandidateDiscoveryData.m_strIsClientInstalled)

g_objLog.WriteLog "Microsoft.FEP.ProtectedServerCandidate.DS.vbs", LOG_INFO, " g_objProtectedServerCandidateDiscoveryData.m_strProductVersion = " &amp; g_objProtectedServerCandidateDiscoveryData.m_strProductVersion
Call g_oInst.AddProperty("$MPElement[Name='Microsoft.FEP.ProtectedServerCandidate']/ClientVer$", g_objProtectedServerCandidateDiscoveryData.m_strProductVersion)

Call g_oInst.AddProperty("$MPElement[Name='System!System.Entity']/DisplayName$", g_ServerId)

Call g_oDiscoveryData.AddInstance(g_oInst) ' Try to submit the discovery, even if some parameters are missing

If Err.Number &lt;&gt; 0 Then
g_objLog.WriteLog "Microsoft.FEP.ProtectedServerCandidate.DS.vbs", LOG_ERROR, "Add property error, error:" + CStr(Err.Number)
Err.Clear
CreateProtectedServerCandidate = False
End If

' If client is not installed, create an instance of Unprotected Server class
If g_objProtectedServerCandidateDiscoveryData.m_strIsClientInstalled = "False" Then

Set g_oInst = Nothing
Set g_oInst = g_oDiscoveryData.CreateClassInstance("$MPElement[Name='Microsoft.FEP.UnprotectedServer']$")
Call g_oInst.AddProperty("$MPElement[Name='Windows!Microsoft.Windows.Computer']/PrincipalName$", g_ServerId)
Call g_oInst.AddProperty("$MPElement[Name='Microsoft.FEP.UnprotectedServer']/ServerId$", g_ServerId)

g_objLog.WriteLog "Microsoft.FEP.ProtectedServerCandidate.DS.vbs", LOG_INFO, " g_objProtectedServerCandidateDiscoveryData.m_strDeploymentState = " &amp; g_objProtectedServerCandidateDiscoveryData.m_strDeploymentState
Call g_oInst.AddProperty("$MPElement[Name='Microsoft.FEP.UnprotectedServer']/DeploymentState$", g_objProtectedServerCandidateDiscoveryData.m_strDeploymentState)

g_objLog.WriteLog "Microsoft.FEP.ProtectedServerCandidate.DS.vbs", LOG_INFO, " g_objProtectedServerCandidateDiscoveryData.m_strDeploymentStateMoreInfo = " &amp; g_objProtectedServerCandidateDiscoveryData.m_strDeploymentStateMoreInfo
Call g_oInst.AddProperty("$MPElement[Name='Microsoft.FEP.UnprotectedServer']/DeploymentStateMoreInfo$", g_objProtectedServerCandidateDiscoveryData.m_strDeploymentStateMoreInfo)

Call g_oInst.AddProperty("$MPElement[Name='Microsoft.FEP.UnprotectedServer']/OperatingSystem$", g_OperatingSystem)
Call g_oInst.AddProperty("$MPElement[Name='System!System.Entity']/DisplayName$", g_ServerId)

If Err.Number &lt;&gt; 0 Then
g_objLog.WriteLog "Microsoft.FEP.ProtectedServerCandidate.DS.vbs", LOG_ERROR, "Add property error, error:" + CStr(Err.Number)
Err.Clear
CreateProtectedServerCandidate = False
End If

Call g_oDiscoveryData.AddInstance(g_oInst) ' Try to submit the discovery, even if some parameters are missing
End If

Call g_objAPI.Return(g_oDiscoveryData)
If Err.Number &lt;&gt; 0 Then
g_objLog.WriteLog "Microsoft.FEP.ProtectedServerCandidate.DS.vbs", LOG_ERROR, "Error submitting discovery data, error:" + CStr(Err.Number)
Err.Clear
CreateProtectedServerCandidate = False
Exit Function
End If
End Function



Dim g_objLog, g_objRegistry
Dim g_bIs64Bit, g_iResult
Dim g_objProtectedServerCandidateDiscoveryData

Dim g_objWSHShell
Dim oArgs
Dim g_oDiscoveryData, g_oInst
Dim g_SourceID, g_ManagedEntityId, g_ServerId, g_OperatingSystem, g_bIsValid
Dim DeploymentInfo, DeploymentResult, DeploymentState


Function Init()
Dim bLogInitialized
On Error Resume Next

Set g_objLog = New CLog
Set g_objRegistry = New CRegistry
Set g_objProtectedServerCandidateDiscoveryData = New CServerCandidateDiscoveryData

g_bIs64Bit = IsOS64Bit()
bLogInitialized = g_objLog.Init("ProtectedServerCandidate.log")

g_objLog.WriteLog "Init", LOG_INFO, "Started"

If IsError(g_bIs64Bit) Or Not bLogInitialized Then
g_objLog.WriteLog "Init", LOG_ERROR, "Cannot initialize"
Init = False
Else
g_objLog.WriteLog "Init", LOG_INFO, "Initialized successfully"
Init = True
End If

End Function

Function ProtectedServerCandidateDiscovery(objProtectedServerCandidateDiscoveryData)
Dim objServerCandidateRegOperator

On Error Resume Next
Err.Clear

g_objLog.WriteLog "ProtectedServerCandidateCandidateDiscovery", LOG_INFO, "ProtectedServerCandidateDiscovery started"
Set objServerCandidateRegOperator = New CServerCandidateRegOperator

ProtectedServerCandidateDiscovery = True

If objServerCandidateRegOperator.GetData(objProtectedServerCandidateDiscoveryData) Then
g_objLog.WriteLog "ProtectedServerCandidateDiscovery", LOG_INFO, "Reg &amp; WMI candidate data retrieved successfully"
g_objLog.WriteLog "ProtectedServerCandidateDiscovery", LOG_INFO, "ProtectedServerCandidate Discovery finished successfully"
ProtectedServerCandidateDiscovery = True
Else
g_objLog.WriteLog "ProtectedServerCandidateDiscovery", LOG_ERROR, "Cannot retrieve Reg &amp; WMI candidate data"
ProtectedServerCandidateDiscovery = False
End If

If Err.Number &lt;&gt; 0 Then
ProtectedServerCandidateDiscovery = False
g_objLog.WriteLog "ProtectedServerCandidateDiscovery", LOG_ERROR, "Cannot execute ProtectedServerCandidateDiscovery, error:" + CStr(Err.Number)
Err.Clear
End If

End Function

'main
On Error Resume Next

SetLocale("en-us")
g_iResult = 0
Do
If Init() Then
g_objLog.WriteLog "Microsoft.FEP.ProtectedServerCandidate.DS.vbs", LOG_INFO, "started"
Else
g_iResult = -1
Exit Do
End If

g_bIsValid = True

' Get arguments

' Microsoft.FEP.MalwareProtection.DS.vbs
' Arg 0 : Element being discovered
' Arg 1 : Target of discovery
' Arg 2 : Hosting server's Id
' Arg 3 : Windows SKU (Server or Client)
Set oArgs = WScript.Arguments
If oArgs.Count = 4 Then
g_SourceID = oArgs(0)
g_ManagedEntityId = oArgs(1)
g_ServerId = oArgs(2)
g_OperatingSystem = oArgs(3)
g_objLog.WriteLog "Microsoft.FEP.ProtectedServerCandidate.DS.vbs", LOG_INFO, "Arguments:" + _
" SourceId: " + g_SourceID + ", ManagedEntityId: " + g_ManagedEntityId + ", ServerId: " + g_ServerId + _
" OperatingSystem: " + g_OperatingSystem
Else
g_objLog.WriteLog "Microsoft.FEP.ProtectedServerCandidate.DS.vbs", LOG_ERROR, "Arguments error, expected 4, received:" + CStr(oArgs.Count)
g_iResult = -1
Exit Do
End If

If Not ProtectedServerCandidateDiscovery(g_objProtectedServerCandidateDiscoveryData) Then
g_iResult = -1
g_bIsValid = False ' The discovery should keep running and create an empty discovery data to avoid SCOM errors
End If

g_objLog.WriteLog "Microsoft.FEP.ProtectedServerCandidate.DS.vbs", LOG_INFO, "Create ProtectedServerCandidate object - start"

g_objLog.SaveLogToDisk
' Create MOM script
If CreateProtectedServerCandidate(g_bIsValid) = False Then
g_iResult = -1
End If
Loop While (False)

If g_iResult = 0 Then
g_objLog.WriteLog "Microsoft.FEP.ProtectedServerCandidate.DS.vbs", LOG_INFO, "Create ProtectedServerCandidate object - end"
Else
g_objLog.WriteLog "Microsoft.FEP.ProtectedServerCandidate.DS.vbs", LOG_ERROR, "failed"
End If

g_objLog.SaveLogToDisk

' Always quit with no error (error code 0) to avoid SCOM errors
WScript.Quit 0


</Script></ScriptBody>
<TimeoutSeconds>$Config/TimeoutSeconds$</TimeoutSeconds>
</DataSource>
</MemberModules>
<Composition>
<Node ID="ProtectedServerCandidateDS"/>
</Composition>
</Composite>
</ModuleImplementation>
<OutputType>System!System.Discovery.Data</OutputType>
</DataSourceModuleType>