home *** CD-ROM | disk | FTP | other *** search
/ PC World Komputer 2010 April / PCWorld0410.iso / WindowsServerTrial / server.iso / sources / install.wim / 5 / Windows / System32 / slmgr.vbs < prev    next >
Text File  |  2008-01-05  |  80KB  |  1,785 lines

  1. '
  2. ' Copyright (c) Microsoft Corporation. All rights reserved.
  3. '
  4. ' Windows Software Licensing Management Tool.
  5. '
  6. ' Script Name: slmgr.vbs
  7. '
  8.  
  9. Dim g_objWMIService, g_strComputer, g_strUserName, g_strPassword
  10. g_strComputer = "."
  11. Dim g_serviceConnected
  12. g_serviceConnected = False
  13.  
  14. dim g_EchoString
  15. g_EchoString = ""
  16.  
  17. dim g_objRegistry
  18.  
  19. Dim g_resourceDictionary, g_resourcesLoaded
  20. Set g_resourceDictionary = CreateObject("Scripting.Dictionary")
  21. g_resourcesLoaded = False
  22.  
  23. ' Messages
  24.  
  25. 'Global options
  26. private const L_optInstallProductKey                  = "ipk"
  27. private const L_optInstallProductKeyUsage             = "Install product key (replaces existing key)"
  28.  
  29. private const L_optUninstallProductKey                = "upk"
  30. private const L_optUninstallProductKeyUsage           = "Uninstall product key"
  31.  
  32. private const L_optActivateProduct                    = "ato"
  33. private const L_optActivateProductUsage               = "Activate Windows"
  34.  
  35. private const L_optDisplayInformation                 = "dli"
  36. private const L_optDisplayInformationUsage            = "Display license information (default: current license)"
  37.  
  38. private const L_optDisplayInformationVerbose          = "dlv"
  39. private const L_optDisplayInformationUsageVerbose     = "Display detailed license information (default: current license)"
  40.  
  41. private const L_optExpirationDatime                   = "xpr"
  42. private const L_optExpirationDatimeUsage              = "Expiration date for current license state"
  43.  
  44. 'Advanced options
  45. private const L_optClearPKeyFromRegistry              = "cpky"
  46. private const L_optClearPKeyFromRegistryUsage         = "Clear product key from the registry (prevents disclosure attacks)"
  47.  
  48. private const L_optInstallLicense                     = "ilc"
  49. private const L_optInstallLicenseUsage                = "Install license"
  50.  
  51. private const L_optReinstallLicenses                  = "rilc"
  52. private const L_optReinstallLicensesUsage             = "Re-install system license files"
  53.  
  54. private const L_optDisplayIID                         = "dti"
  55. private const L_optDisplayIIDUsage                    = "Display Installation ID for offline activation"
  56.  
  57. private const L_optPhoneActivateProduct               = "atp"
  58. private const L_optPhoneActivateProductUsage          = "Activate product with user-provided Confirmation ID"
  59.  
  60. private const L_optReArmWindows                       = "rearm"
  61. private const L_optReArmWindowsUsage                  = "Reset the licensing status of the machine"
  62.  
  63. 'KMS options
  64.  
  65. private const L_optSetKmsName                         = "skms"
  66. private const L_optSetKmsNameUsage                    = "Set the name and/or the port for the KMS computer this machine will use"
  67.  
  68. private const L_optClearKmsName                       = "ckms"
  69. private const L_optClearKmsNameUsage                  = "Clear name of KMS computer used (sets the port to the default)"
  70.  
  71. private const L_optSetActivationInterval              = "sai"
  72. private const L_optSetActivationIntervalUsage         = "Set interval (minutes) for unactivated clients to attempt KMS connection. The activation interval must be between 15 minutes (min) and 30 days (max) although the default (2 hours) is recommended."
  73.  
  74. private const L_optSetRenewalInterval                 = "sri"
  75. private const L_optSetRenewalIntervalUsage            = "Set renewal interval (minutes) for activated clients to attempt KMS connection. The renewal interval must be between 15 minutes (min) and 30 days (max) although the default (7 days) is recommended."
  76.  
  77. private const L_optSetKmsListenPort                   = "sprt"
  78. private const L_optSetKmsListenPortUsage              = "Set TCP port KMS will use to communicate with clients"
  79.  
  80. private const L_optSetDNS                             = "sdns"
  81. private const L_optSetDNSUsage                        = "Enable DNS publishing by KMS (default)"
  82.  
  83. private const L_optClearDNS                           = "cdns"
  84. private const L_optClearDNSUsage                      = "Disable DNS publishing by KMS"
  85.  
  86. private const L_optSetNormalPriority                  = "spri"
  87. private const L_optSetNormalPriorityUsage             = "Set KMS priority to normal (default)"
  88.  
  89. private const L_optClearNormalPriority                = "cpri"
  90. private const L_optClearNormalPriorityUsage           = "Set KMS priority to low"
  91.  
  92. ' Option parameters
  93. private const L_ParamsActivationID                    = "<Activation ID>"
  94. private const L_ParamsActivationIDOptional            = "[Activation ID]"
  95. private const L_ParamsActIDOptional                   = "[Activation ID | All]"
  96. private const L_ParamsProductKey                      = "<Product Key>"
  97. private const L_ParamsLicenseFile                     = "<License file>"
  98. private const L_ParamsPhoneActivate                   = "<Confirmation ID>"
  99. private const L_ParamsSetKms                          = "<Name[:Port] | :Port>"
  100. private const L_ParamsSetListenKmsPort                = "<Port>"
  101. private const L_ParamsSetActivationInterval           = "<Activation Interval>"
  102. private const L_ParamsSetRenewalInterval              = "<Renewal Interval>"
  103.  
  104. ' Miscellaneous messages
  105. private const L_MsgHelp_1                             = "Windows Software Licensing Management Tool"
  106. private const L_MsgHelp_2                             = "Usage: slmgr.vbs [MachineName [User Password]] [<Option>]"
  107. private const L_MsgHelp_3                             = "MachineName: Name of remote machine (default is local machine)"
  108. private const L_MsgHelp_4                             = "User:        Account with required privilege on remote machine"
  109. private const L_MsgHelp_5                             = "Password:    password for the previous account"
  110. private const L_MsgGlobalOptions                      = "Global Options:"
  111. private const L_MsgAdvancedOptions                    = "Advanced Options:"
  112. private const L_MsgKmsClientOptions                   = "Volume Licensing: Key Management Service (KMS) Client Options:"
  113. private const L_MsgKmsOptions                         = "Volume Licensing: Key Management Service (KMS) Options:"
  114. private const L_MsgMissingOption                      = "Option is missing and it must be provided"
  115. private const L_MsgUnrecognizedOption                 = "Unrecognized option: "
  116. private const L_MsgErrorProductNotFound               = "Error: product not found."
  117. private const L_MsgClearedPKey                        = "Product key from registry cleared successfully."
  118. private const L_MsgInstalledPKey                      = "Installed product key %PKEY% successfully."
  119. private const L_MsgUninstalledPKey                    = "Uninstalled product key successfully."
  120. private const L_MsgErrorPKey                          = "Error: product key not found."
  121. private const L_MsgInstallationID                     = "Installation ID: "
  122. private const L_MsgPhoneNumbers                       = "Product activation telephone numbers can be obtained by searching the phone.inf file for the appropriate phone number for your location/country. You can open the phone.inf file from a Command Prompt or the Start Menu by running: notepad %systemroot%\system32\slui\phone.inf"
  123. private const L_MsgActivating                         = "Activating %PRODUCTNAME% (%PRODUCTID%) ..."
  124. private const L_MsgActivated                          = "Product activated successfully."
  125. private const L_MsgActivated_Failed                   = "Error: Product activation failed."
  126. private const L_MsgConfID                             = "Confirmation ID for product %ACTID% deposited successfully."
  127. private const L_MsgErrorDescription                   = "Error description: "
  128. private const L_MsgErrorConnection                    = "Error 0x%ERRCODE% occurred in connecting to server %COMPUTERNAME%."
  129. private const L_MsgErrorConnectionRegistry            = "Error 0x%ERRCODE% occurred in connecting to the registry on server %COMPUTERNAME%."
  130. private const L_MsgErrorConnectionProcessor           = "Error 0x%ERRCODE% occurred in connecting to the processor on server %COMPUTERNAME%."
  131. private const L_MsgErrorImpersonation                 = "Error 0x%ERRCODE% occurred in setting impersonation level."
  132. private const L_MsgErrorWMI                           = "Error 0x%ERRCODE% occurred in creating a locator object."
  133. private const L_MsgErrorText_1                        = "Access denied: the requested action requires elevated privileges."
  134. private const L_MsgErrorText_2                        = "Could not find a KMS machine."
  135. private const L_MsgErrorText_3                        = "The software licensing service reported that the requested permission is not available."
  136. private const L_MsgErrorText_4                        = "The computer could not be activated. The returned count from your Key Management Service is insufficient."
  137. private const L_MsgErrorText_5                        = "The computer could not be activated. The Key Management Service could not be reached."
  138. private const L_MsgErrorText_6                        = "Run 'slui.exe 0x2a 0x%ERRCODE%' to display the error text."
  139. private const L_MsgErrorText_8                        = "Error: "
  140. private const L_MsgErrorText_9                        = "Error: option %OPTION% needs %PARAM%"
  141. private const L_MsgErrorText_10                       = "The maximum allowed number of re-arms has been exceeded. You must re-install the OS before trying to re-arm again."
  142. private const L_MsgErrorText_11                       = "The machine is running within the non-genuine grace period. Please run 'slui.exe 0x31' to go online and make the machine genuine."
  143. private const L_MsgErrorText_12                       = "Windows is running within the non-genuine notification period. Please run 'slui.exe 0x31' to go online and validate Windows."
  144. private const L_MsgLicenseFile                        = "License file %LICENSEFILE% installed successfully."
  145. private const L_MsgKmsPriSetToLow                     = "KMS priority set to Low"
  146. private const L_MsgKmsPriSetToNormal                  = "KMS priority set to Normal"
  147. private const L_MsgWarningKmsPri                      = "Warning: Priority can only be set on a KMS machine that is also activated."
  148. private const L_MsgKmsDnsPublishingDisabled           = "DNS publishing disabled"
  149. private const L_MsgKmsDnsPublishingEnabled            = "DNS publishing enabled"
  150. private const L_MsgKmsDnsPublishingWarning            = "Warning: DNS Publishing can only be set on a KMS machine that is also activated."
  151. private const L_MsgKmsPortSet                         = "KMS port set to %PORT% successfully."
  152. private const L_MsgWarningKmsReboot                   = "Warning: a KMS reboot is needed for this setting to take effect."
  153. private const L_MsgWarningKmsPort                     = "Warning: KMS port can only be set on a KMS machine that is also activated."
  154. private const L_MsgRenewalSet                         = "Volume renewal interval set to %RENEWAL% minutes successfully."
  155. private const L_MsgWarningRenewal                     = "Warning: Volume renewal interval can only be set on a KMS machine that is also activated."
  156. private const L_MsgActivationSet                      = "Volume activation interval set to %ACTIVATION% minutes successfully."
  157. private const L_MsgWarningActivation                  = "Warning: Volume activation interval can only be set on a KMS machine that is also activated."
  158. private const L_MsgKmsNameSet                         = "Key Management Service machine name set to %KMS% successfully."
  159. private const L_MsgKmsNameCleared                     = "Key Management Service machine name cleared successfully."
  160. private const L_MsgRearm_1                            = "Command completed successfully."
  161. private const L_MsgRearm_2                            = "Please restart the system for the changes to take effect."
  162. private const L_MsgLicenseStatusUnlicensed            = "Windows is unlicensed"
  163. private const L_MsgLicenseStatusVL                    = "Volume activation will expire %ENDDATE%"
  164. private const L_MsgLicenseStatusLicensed              = "The machine is permanently activated."
  165. private const L_MsgLicenseStatusInitialGrace          = "Initial grace period ends %ENDDATE%"
  166. private const L_MsgLicenseStatusAdditionalGrace       = "Additional grace period ends %ENDDATE%"
  167. private const L_MsgLicenseStatusNonGenuineGrace       = "Non-genuine grace period ends %ENDDATE%"
  168. private const L_MsgLicenseStatusNotification          = "Windows is in Notification mode"
  169. private const L_MsgLicenseStatusUnlicensed_1          = "License Status: Unlicensed"
  170. private const L_MsgLicenseStatusLicensed_1            = "License Status: Licensed"
  171. private const L_MsgLicenseStatusVL_1                  = "Volume activation expiration: %MINUTE% minute(s) (%DAY% day(s))"
  172. private const L_MsgLicenseStatusInitialGrace_1        = "License Status: Initial grace period"
  173. private const L_MsgLicenseStatusAdditionalGrace_1     = "License Status: Additional grace period (KMS license expired or hardware out of tolerance)"
  174. private const L_MsgLicenseStatusNonGenuineGrace_1     = "License Status: Non-genuine grace period."
  175. private const L_MsgLicenseStatusNotification_1        = "License Status: Notification"
  176. private const L_MsgNotificationErrorReasonNonGenuine  = "Notification Reason: 0x%ERRCODE% (non-genuine)."
  177. private const L_MsgNotificationErrorReasonExpiration  = "Notification Reason: 0x%ERRCODE% (grace time expired)."
  178. private const L_MsgNotificationErrorReasonOther       = "Notification Reason: 0x%ERRCODE%."
  179. private const L_MsgLicenseStatusTimeRemaining         = "Time remaining: %MINUTE% minute(s) (%DAY% day(s))"
  180. private const L_MsgLicenseStatusUnknown               = "License Status: Unknown"
  181. private const L_MsgLicenseStatusEvalEndData           = "Evaluation End Date: "
  182. private const L_MsgReinstallingLicenses               = "Re-installing license files ..."
  183. private const L_MsgLicensesReinstalled                = "License files re-installed successfully."
  184. private const L_MsgServiceVersion                     = "Software licensing service version: "
  185. private const L_MsgProductName                        = "Name: "
  186. private const L_MsgProductDesc                        = "Description: "
  187. private const L_MsgActID                              = "Activation ID: "
  188. private const L_MsgAppID                              = "Application ID: "
  189. private const L_MsgPID4                               = "Extended PID: "
  190. private const L_MsgProcessorCertUrl                   = "Processor Certificate URL: "
  191. private const L_MsgMachineCertUrl                     = "Machine Certificate URL: "
  192. private const L_MsgUseLicenseCertUrl                  = "Use License URL: "
  193. private const L_MsgPKeyCertUrl                        = "Product Key Certificate URL: "
  194. private const L_MsgPartialPKey                        = "Partial Product Key: "
  195. private const L_MsgErrorLicenseNotInUse               = "This license is not in use."
  196. private const L_MsgKmsInfo                            = "Key Management Service client information"
  197. private const L_MsgCmid                               = "Client Machine ID (CMID): "
  198. private const L_MsgRegisteredKmsName                  = "Registered KMS machine name: "
  199. private const L_MsgKmsFromDnsUnavailable              = "DNS auto-discovery: KMS name not available"
  200. private const L_MsgKmsFromDns                         = "KMS machine name from DNS: "
  201. private const L_MsgKmsPID4                            = "KMS machine extended PID: "
  202. private const L_MsgActivationInterval                 = "Activation interval: %INTERVAL% minutes"
  203. private const L_MsgRenewalInterval                    = "Renewal interval: %INTERVAL% minutes"
  204. private const L_MsgKmsEnabled                         = "Key Management Service is enabled on this machine"
  205. private const L_MsgKmsCurrentCount                    = "Current count: "
  206. private const L_MsgKmsListeningOnPort                 = "Listening on Port: "
  207. private const L_MsgKmsPriNormal                       = "KMS priority: Normal"
  208. private const L_MsgKmsPriLow                          = "KMS priority: Low"
  209. private const L_MsgInvalidDataError                   = "Error: The data is invalid"
  210. private const L_MsgUndeterminedPrimaryKey             = "Warning: SLMGR was not able to validate the current product key for Windows. Please upgrade to the latest service pack."
  211. private const L_MsgUndeterminedPrimaryKeyOperation    = "Warning: This operation may affect more than one target license.  Please verify the results."
  212. private const L_MsgUndeterminedOperationFormat        = "Processing the license for %PRODUCTDESCRIPTION% (%PRODUCTID%)."
  213.  
  214. private const L_MsgKmsCumulativeRequestsFromClients             = "Key Management Service cumulative requests received from clients"
  215. private const L_MsgKmsTotalRequestsRecieved                     = "Total requests received: "
  216. private const L_MsgKmsFailedRequestsReceived                    = "Failed requests received: "
  217. private const L_MsgKmsRequestsWithStatusUnlicensed              = "Requests with License Status Unlicensed: "
  218. private const L_MsgKmsRequestsWithStatusLicensed                = "Requests with License Status Licensed: "
  219. private const L_MsgKmsRequestsWithStatusInitialGrace            = "Requests with License Status Initial grace period: "
  220. private const L_MsgKmsRequestsWithStatusLicenseExpiredOrHwidOot = "Requests with License Status License expired or Hardware out of tolerance: "
  221. private const L_MsgKmsRequestsWithStatusNonGenuineGrace         = "Requests with License Status Non-genuine grace period: "
  222. private const L_MsgKmsRequestsWithStatusNotification            = "Requests with License Status Notification: "
  223. private const NoPrimaryKeyFound                       = "NoPrimaryKeyFound"
  224. private const NonKMSPrimaryKey                        = "NonKMSPrimaryKey"
  225. private const IndeterminatePrimaryKeyFound            = "IndeterminatePrimaryKey"
  226.  
  227. ' Registry constants
  228. private const HKEY_LOCAL_MACHINE                      = &H80000002
  229. private const HKEY_NETWORK_SERVICE                    = &H80000003
  230.  
  231. private const DefaultPort                             = "1688"
  232. private const intKnownOption                          = 0
  233. private const intUnknownOption                        = 1
  234.  
  235. private const SLKeyPath                               = "SOFTWARE\Microsoft\Windows NT\CurrentVersion\SL"
  236. private const SLKeyPath32                             = "SOFTWARE\Wow6432Node\Microsoft\Windows NT\CurrentVersion\SL"
  237. private const NSKeyPath                               = "S-1-5-20\SOFTWARE\Microsoft\Windows NT\CurrentVersion\SL"
  238.  
  239. private const HR_S_OK                                 = 0
  240. private const HR_ERROR_FILE_NOT_FOUND                 = &H80070002
  241. private const HR_SL_E_GRACE_TIME_EXPIRED              = &HC004F009
  242. private const HR_SL_E_NOT_GENUINE                     = &HC004F200
  243.  
  244. ' WMI class names
  245. private const ServiceClass                            = "SoftwareLicensingService"
  246. private const ProductClass                            = "SoftwareLicensingProduct"
  247. private const WindowsAppId                            = "55c92734-d682-4d71-983e-d6ec3f16059f"
  248.  
  249. Call ExecCommandLine()
  250. ExitScript 0
  251.  
  252. Private Sub DisplayUsage (bShowKmsInfo, bShowKmsClientInfo)
  253.     LineOut GetResource("L_MsgHelp_1")
  254.     LineOut GetResource("L_MsgHelp_2")
  255.     LineOut "           " & GetResource("L_MsgHelp_3")
  256.     LineOut "           " & GetResource("L_MsgHelp_4")
  257.     LineOut "           " & GetResource("L_MsgHelp_5")
  258.     LineOut ""
  259.     LineOut GetResource("L_MsgGlobalOptions")
  260.     OptLine GetResource("L_optInstallProductKey"),         GetResource("L_ParamsProductKey"),         GetResource("L_optInstallProductKeyUsage")
  261.     OptLine GetResource("L_optActivateProduct"),           "",                                        GetResource("L_optActivateProductUsage")
  262.     OptLine GetResource("L_optDisplayInformation"),        GetResource("L_ParamsActIDOptional"),      GetResource("L_optDisplayInformationUsage")
  263.     OptLine GetResource("L_optDisplayInformationVerbose"), GetResource("L_ParamsActIDOptional"),      GetResource("L_optDisplayInformationUsageVerbose")
  264.     OptLine GetResource("L_optExpirationDatime"),          "",                                        GetResource("L_optExpirationDatimeUsage")
  265.     LineOut ""
  266.     LineOut GetResource("L_MsgAdvancedOptions")
  267.     OptLine GetResource("L_optClearPKeyFromRegistry"),     "",                                        GetResource("L_optClearPKeyFromRegistryUsage")
  268.     OptLine GetResource("L_optInstallLicense"),            GetResource("L_ParamsLicenseFile"),        GetResource("L_optInstallLicenseUsage")
  269.     OptLine GetResource("L_optReinstallLicenses"),         "",                                        GetResource("L_optReinstallLicensesUsage")
  270.     OptLine GetResource("L_optReArmWindows"),              "",                                        GetResource("L_optReArmWindowsUsage")
  271.     OptLine GetResource("L_optUninstallProductKey"),       "",                                        GetResource("L_optUninstallProductKeyUsage")
  272.     
  273.     If bShowKmsClientInfo = False Then
  274.         OptLine GetResource("L_optDisplayIID"),            "",                                        GetResource("L_optDisplayIIDUsage")
  275.         OptLine GetResource("L_optPhoneActivateProduct"),  GetResource("L_ParamsPhoneActivate"),      GetResource("L_optPhoneActivateProductUsage")
  276.     End If
  277.  
  278.     LineOut ""
  279.  
  280.     If bShowKmsClientInfo Then
  281.         LineOut GetResource("L_MsgKmsClientOptions")
  282.         OptLine GetResource("L_optSetKmsName"),            GetResource("L_ParamsSetKms"),             GetResource("L_optSetKmsNameUsage")
  283.         OptLine GetResource("L_optClearKmsName"),          "",                                        GetResource("L_optClearKmsNameUsage")
  284.     End If
  285.  
  286.     If bShowKmsInfo Then
  287.         LineOut GetResource("L_MsgKmsOptions")
  288.         OptLine GetResource("L_optSetKmsListenPort"),      GetResource("L_ParamsSetListenKmsPort"),   GetResource("L_optSetKmsListenPortUsage")
  289.         OptLine GetResource("L_optSetActivationInterval"), GetResource("L_ParamsSetActivationInterval"),GetResource("L_optSetActivationIntervalUsage")
  290.         OptLine GetResource("L_optSetRenewalInterval"),    GetResource("L_ParamsSetRenewalInterval"), GetResource("L_optSetRenewalIntervalUsage")
  291.         OptLine GetResource("L_optSetDNS"),                "",                                        GetResource("L_optSetDNSUsage")
  292.         OptLine GetResource("L_optClearDNS"),              "",                                        GetResource("L_optClearDNSUsage")
  293.         OptLine GetResource("L_optSetNormalPriority"),     "",                                        GetResource("L_optSetNormalPriorityUsage")
  294.         OptLine GetResource("L_optClearNormalPriority"),   "",                                        GetResource("L_optClearNormalPriorityUsage")
  295.     End If
  296.  
  297.     ExitScript 1
  298. End Sub
  299.  
  300. Private Sub OptLine(strOption, strParams, strUsage)
  301.     LineOut "-" & strOption & " " & strParams
  302.     LineOut "    " & strUsage
  303. End Sub
  304.  
  305. Private Sub ExecCommandLine
  306.     Dim bShowKmsInfo, bShowKmsClientInfo, strDescription, strPrimarySkuType
  307.     Dim intOption, indexOption
  308.     
  309.     'WMI connection to local provider
  310.     If Not booleanConnect() Then
  311.         Exit Sub
  312.     End If
  313.  
  314.     bShowKmsInfo = False
  315.     bShowKmsClientInfo = False
  316.     strPrimarySkuType = GetPrimarySKUType()
  317.     If (WasPrimaryKeyFound(strPrimarySkuType)) Then
  318.         If (CanPrimaryKeyTypeBeDetermined(strPrimarySkuType)) Then
  319.             If (IsKmsServer(strPrimarySkuType)) Then
  320.                 bShowKmsInfo = True
  321.             ElseIf (IsKMSClient(strPrimarySkuType)) Then
  322.                 bShowKmsClientInfo = True
  323.             End If
  324.         Else
  325.             'We can't determine the primary key type!
  326.             LineOut GetResource("L_MsgUndeterminedPrimaryKey")
  327.         End If
  328.     End If
  329.  
  330.     If WScript.Arguments.Count = 0 Then
  331.         Call DisplayUsage(bShowKmsInfo, bShowKmsClientInfo)
  332.     End If
  333.  
  334.     intOption = ParseCommandLine(bShowKmsInfo, bShowKmsClientInfo, 0)
  335.     If intOption = intUnknownOption Then
  336.  
  337.         If WScript.Arguments.Count = 1 Then
  338.             LineOut GetResource("L_MsgUnrecognizedOption") & WScript.Arguments.Item(0)
  339.             Call DisplayUsage(bShowKmsInfo, bShowKmsClientInfo)
  340.         End If
  341.  
  342.         If WScript.Arguments.Count <= 3 Then
  343.             g_strComputer = WScript.Arguments.Item(0)
  344.             indexOption = 1
  345.         Else
  346.             'assume the command line contains a machine
  347.             ' name, user name and a password
  348.             g_strComputer = WScript.Arguments.Item(0)
  349.             g_strUserName = WScript.Arguments.Item(1)
  350.             g_strPassword = WScript.Arguments.Item(2)
  351.             indexOption = 3
  352.         End If
  353.  
  354.         're-connect to remote machine if needed
  355.         If g_strComputer <> "" Then
  356.             If Not booleanConnect() Then
  357.                 Exit Sub
  358.             End If
  359.         End If
  360.  
  361.         're-evaluate the type of the remote machine
  362.         bShowKmsInfo = False
  363.         bShowKmsClientInfo = False
  364.         strPrimarySkuType = GetPrimarySKUType()
  365.         If (WasPrimaryKeyFound(strPrimarySkuType)) Then
  366.             If (CanPrimaryKeyTypeBeDetermined(strPrimarySkuType)) Then
  367.                 If (IsKmsServer(strPrimarySkuType)) Then
  368.                     bShowKmsInfo = True
  369.                 ElseIf (IsKMSClient(strPrimarySkuType)) Then
  370.                     bShowKmsClientInfo = True
  371.                 End If
  372.             Else
  373.                 'We can't determine the primary key type!
  374.                 LineOut GetResource("L_MsgUndeterminedPrimaryKey")
  375.             End If
  376.         End If
  377.     
  378.         'try second command line param
  379.         intOption = ParseCommandLine(bShowKmsInfo, bShowKmsClientInfo, indexOption)
  380.         If intUnknownOption = intOption Then
  381.             LineOut GetResource("L_MsgUnrecognizedOption") & WScript.Arguments.Item(indexOption)
  382.             Call DisplayUsage(bShowKmsInfo, bShowKmsClientInfo)
  383.         End If
  384.     End If
  385. End Sub
  386.  
  387. Private Function ParseCommandLine(bShowKmsInfo, bShowKmsClientInfo, index)
  388.     Dim strOption, chOpt
  389.  
  390.     ParseCommandLine = intKnownOption
  391.  
  392.     strOption = LCase(WScript.Arguments.Item(index))
  393.  
  394.     chOpt = Left(strOption, 1)
  395.  
  396.     If (chOpt <> "-") And (chOpt <> "/") Then
  397.         ParseCommandLine = intUnknownOption
  398.         Exit Function
  399.     End If
  400.  
  401.     strOption = Right(strOption, Len(strOption) - 1)
  402.  
  403.     If strOption = GetResource("L_optInstallLicense") Then
  404.  
  405.         If HandleOptionParam(bShowKmsInfo, bShowKmsClientInfo, index+1, True, GetResource("L_optInstallLicense"), GetResource("L_ParamsLicenseFile")) Then
  406.             InstallLicense WScript.Arguments.Item(index+1)
  407.         End If
  408.  
  409.     ElseIf strOption = GetResource("L_optInstallProductKey") Then
  410.  
  411.         If HandleOptionParam(bShowKmsInfo, bShowKmsClientInfo, index+1, True, GetResource("L_optInstallProductKey"), GetResource("L_ParamsProductKey")) Then
  412.             InstallProductKey WScript.Arguments.Item(index+1)
  413.         End If
  414.  
  415.     ElseIf strOption = GetResource("L_optUninstallProductKey") Then
  416.  
  417.         UninstallProductKey
  418.  
  419.     ElseIf (strOption = GetResource("L_optDisplayIID") And bShowKmsClientInfo = False) Then
  420.  
  421.         DisplayIID
  422.  
  423.     ElseIf strOption = GetResource("L_optActivateProduct") Then
  424.  
  425.         ActivateProduct
  426.  
  427.     ElseIf (strOption = GetResource("L_optPhoneActivateProduct") And bShowKmsClientInfo = False) Then
  428.  
  429.         If HandleOptionParam(bShowKmsInfo, bShowKmsClientInfo, index+1, True, GetResource("L_optPhoneActivateProduct"), GetResource("L_ParamsPhoneActivate")) Then
  430.             PhoneActivateProduct WScript.Arguments.Item(index+1)
  431.         End If
  432.  
  433.     ElseIf strOption = GetResource("L_optDisplayInformation") Then
  434.  
  435.         If HandleOptionParam(bShowKmsInfo, bShowKmsClientInfo, index+1, False, GetResource("L_optDisplayInformation"), "") Then
  436.             DisplayAllInformation WScript.Arguments.Item(index+1), False
  437.         Else
  438.             DisplayAllInformation "", False
  439.         End If
  440.  
  441.     ElseIf strOption = GetResource("L_optDisplayInformationVerbose") Then
  442.  
  443.         If HandleOptionParam(bShowKmsInfo, bShowKmsClientInfo, index+1, False, GetResource("L_optDisplayInformationVerbose"), "") Then
  444.             DisplayAllInformation WScript.Arguments.Item(index+1), True
  445.         Else
  446.             DisplayAllInformation "", True
  447.         End If
  448.  
  449.     ElseIf strOption = GetResource("L_optClearPKeyFromRegistry") Then
  450.  
  451.         ClearPKeyFromRegistry
  452.  
  453.     ElseIf strOption = GetResource("L_optReinstallLicenses") Then
  454.  
  455.         ReinstallLicenses
  456.  
  457.     ElseIf strOption = GetResource("L_optReArmWindows") Then
  458.  
  459.         ReArmWindows()
  460.  
  461.     ElseIf strOption = GetResource("L_optExpirationDatime") Then
  462.  
  463.         ExpirationDatime()
  464.  
  465.     ElseIf (strOption = GetResource("L_optSetKmsName") And bShowKmsClientInfo = True) Then
  466.  
  467.         If HandleOptionParam(bShowKmsInfo, bShowKmsClientInfo, index+1, True, GetResource("L_optSetKmsName"), GetResource("L_ParamsSetKms")) Then
  468.             SetKmsMachineName WScript.Arguments.Item(index+1)
  469.         End If
  470.  
  471.     ElseIf (strOption = GetResource("L_optClearKmsName") And bShowKmsClientInfo = True) Then
  472.  
  473.         ClearKms
  474.  
  475.     ElseIf (strOption = GetResource("L_optSetActivationInterval") And bShowKmsInfo = True) Then
  476.  
  477.         If HandleOptionParam(bShowKmsInfo, bShowKmsClientInfo, index+1, True, GetResource("L_optSetActivationInterval"), GetResource("L_ParamsSetActivationInterval")) Then
  478.             SetActivationInterval  WScript.Arguments.Item(index+1)
  479.         End If
  480.  
  481.     ElseIf (strOption = GetResource("L_optSetRenewalInterval") And bShowKmsInfo = True) Then
  482.  
  483.         If HandleOptionParam(bShowKmsInfo, bShowKmsClientInfo, index+1, True, GetResource("L_optSetRenewalInterval"), GetResource("L_ParamsSetRenewalInterval")) Then
  484.             SetRenewalInterval  WScript.Arguments.Item(index+1)
  485.         End If
  486.  
  487.     ElseIf (strOption = GetResource("L_optSetKmsListenPort") And bShowKmsInfo = True) Then
  488.  
  489.         If HandleOptionParam(bShowKmsInfo, bShowKmsClientInfo, index+1, True, GetResource("L_optSetKmsListenPort"), GetResource("L_ParamsSetKmsListenPort")) Then
  490.             SetKmsListenPort WScript.Arguments.Item(index+1)
  491.         End If
  492.  
  493.     ElseIf (strOption = GetResource("L_optSetDNS") And bShowKmsInfo = True) Then
  494.  
  495.         SetDnsPublishingDisabled(False)
  496.  
  497.     ElseIf (strOption = GetResource("L_optClearDNS") And bShowKmsInfo = True) Then
  498.  
  499.         SetDnsPublishingDisabled(True)
  500.  
  501.     ElseIf (strOption = GetResource("L_optSetNormalPriority") And bShowKmsInfo = True) Then
  502.  
  503.         SetKmsLowPriority(False)
  504.  
  505.     ElseIf (strOption = GetResource("L_optClearNormalPriority") And bShowKmsInfo = True) Then
  506.  
  507.         SetKmsLowPriority(True)
  508.  
  509.     Else
  510.  
  511.         ParseCommandLine = intUnknownOption
  512.  
  513.     End If
  514.  
  515. End Function
  516.  
  517. ' global options
  518.  
  519. Private Sub UninstallProductKey()
  520.     Dim objProduct
  521.     Dim lRet
  522.     Dim iIsPrimaryWindowsSku, bAtLeastOnKeyUninstalled
  523.  
  524.  
  525.     ' Clear the KMS version from the registry (both 64 and 32 bit locations)
  526.     lRet = DeleteRegistryValue(HKEY_LOCAL_MACHINE, SLKeyPath, "KeyManagementServiceVersion")
  527.     If (lRet <> 0 And lRet <> 2) Then
  528.         QuitWithError CStr(Hex(lRet))
  529.     End If
  530.  
  531.     lRet = DeleteRegistryValue(HKEY_LOCAL_MACHINE, SLKeyPath32, "KeyManagementServiceVersion")
  532.     If (lRet <> 0 And lRet <> 2) Then
  533.         QuitWithError CStr(Hex(lRet))
  534.     End If
  535.  
  536.     bAtLeastOnKeyUninstalled = False
  537.     For Each objProduct in g_objWMIService.InstancesOf(ProductClass)
  538.         iIsPrimaryWindowsSku = GetIsPrimaryWindowsSKU(objProduct)
  539.         If ((iIsPrimaryWindowsSku = 1) Or (iIsPrimaryWindowsSku = 2)) Then
  540.             If (iIsPrimaryWindowsSku = 2) Then
  541.                 OutputIndeterminateOperationWarning(objProduct)
  542.             End If
  543.             On Error Resume Next
  544.             objProduct.UninstallProductKey()
  545.             QuitIfError()
  546.             LineOut GetResource("L_MsgUninstalledPKey")
  547.             If (iIsPrimaryWindowsSku = 1) Then
  548.                 Exit Sub
  549.             Else
  550.                 bAtLeastOnKeyUninstalled = True
  551.             End If
  552.         End If
  553.     Next
  554.  
  555.     If (bAtLeastOnKeyUninstalled = False) Then
  556.         Exit Sub
  557.     End If
  558.  
  559.     LineOut GetResource("L_MsgErrorPKey")
  560. End Sub
  561.  
  562. Private Sub DisplayIID()
  563.     Dim objProduct
  564.     Dim iIsPrimaryWindowsSku, bFoundAtLeastOneKey
  565.  
  566.     bFoundAtLeastOneKey = False
  567.     For Each objProduct in g_objWMIService.InstancesOf(ProductClass)
  568.         iIsPrimaryWindowsSku = GetIsPrimaryWindowsSKU(objProduct)
  569.         If (1 = iIsPrimaryWindowsSku) Then
  570.             LineOut GetResource("L_MsgInstallationID") & objProduct.OfflineInstallationId
  571.             LineOut ""
  572.             LineOut GetResource("L_MsgPhoneNumbers")
  573.             Exit Sub
  574.         ElseIf (2 = iIsPrimaryWindowsSku) Then
  575.             OutputIndeterminateOperationWarning(objProduct)
  576.             LineOut GetResource("L_MsgInstallationID") & objProduct.OfflineInstallationId
  577.             bFoundAtLeastOneKey = TRUE
  578.         End If
  579.     Next
  580.     
  581.     If (bFoundAtLeastOneKey = TRUE) Then
  582.         LineOut ""
  583.         LineOut GetResource("L_MsgPhoneNumbers")
  584.         Exit Sub
  585.     End If    
  586.     
  587.     LineOut GetResource("L_MsgErrorProductNotFound")
  588. End Sub
  589.  
  590. Private Sub ActivateProduct()
  591.     Dim objService, objProduct
  592.     Dim strOutput
  593.     Dim iIsPrimaryWindowsSku, bFoundAtLeastOneKey
  594.  
  595.     bFoundAtLeastOneKey = False
  596.     For Each objService in g_objWMIService.InstancesOf(ServiceClass)
  597.         For Each objProduct in g_objWMIService.InstancesOf(ProductClass)
  598.             iIsPrimaryWindowsSku = GetIsPrimaryWindowsSKU(objProduct)
  599.             If ((iIsPrimaryWindowsSku = 1) Or (iIsPrimaryWindowsSku = 2)) Then
  600.                 If (iIsPrimaryWindowsSku = 2) Then
  601.                     OutputIndeterminateOperationWarning(objProduct)
  602.                 End If
  603.                 strOutput = Replace(GetResource("L_MsgActivating"), "%PRODUCTNAME%", objProduct.Name)
  604.                 strOutput = Replace(strOutput, "%PRODUCTID%", objProduct.ID)
  605.                 LineOut strOutput
  606.                 On Error Resume Next
  607.                 objProduct.Activate()
  608.                 QuitIfError()
  609.                 objService.RefreshLicenseStatus()
  610.                 objProduct.refresh_
  611.                 If (objProduct.LicenseStatus = 1) Then
  612.                     LineOut GetResource("L_MsgActivated")
  613.                 ElseIf (objProduct.LicenseStatus = 4) Then
  614.                     LineOut GetResource("L_MsgErrorText_8") & GetResource("L_MsgErrorText_11")
  615.                 ElseIf ((objProduct.LicenseStatus = 5) And (objProduct.LicenseStatusReason = HR_SL_E_NOT_GENUINE)) Then
  616.                     LineOut GetResource("L_MsgErrorText_8") & GetResource("L_MsgErrorText_12")
  617.                 Else
  618.                     LineOut GetResource("L_MsgActivated_Failed")
  619.                 End If
  620.                 
  621.                 If (1 = iIsPrimaryWindowsSku) Then
  622.                     Exit Sub
  623.                 Else
  624.                     'Keep going in case there are other active SKUs...
  625.                     bFoundAtLeastOneKey = TRUE
  626.                 End If
  627.             End If
  628.         Next
  629.     Next
  630.     
  631.     If (bFoundAtLeastOneKey = TRUE) Then
  632.         Exit Sub
  633.     End If
  634.     
  635.     LineOut GetResource("L_MsgErrorProductNotFound")
  636. End Sub
  637.  
  638. Private Sub PhoneActivateProduct(strCID)
  639.     Dim objService, objProduct
  640.     Dim iIsPrimaryWindowsSku, bFoundAtLeastOneKey
  641.  
  642.     bFoundAtLeastOneKey = False
  643.     For Each objService in g_objWMIService.InstancesOf(ServiceClass)
  644.         For Each objProduct in g_objWMIService.InstancesOf(ProductClass)
  645.             iIsPrimaryWindowsSku = GetIsPrimaryWindowsSKU(objProduct)
  646.             If (iIsPrimaryWindowsSku = 1) Or (iIsPrimaryWindowsSku = 2) Then
  647.                 If (iIsPrimaryWindowsSku = 2) Then
  648.                     OutputIndeterminateOperationWarning(objProduct)
  649.                 End If
  650.                 
  651.                 On Error Resume Next
  652.                 objProduct.DepositOfflineConfirmationId objProduct.OfflineInstallationId, strCID
  653.                 QuitIfError()
  654.                 objService.RefreshLicenseStatus()
  655.                 objProduct.refresh_
  656.                 If (objProduct.LicenseStatus = 1) Then
  657.                     strOutput = Replace(GetResource("L_MsgConfID"), "%ACTID%", objProduct.ID)
  658.                     LineOut strOutput
  659.                 ElseIf (objProduct.LicenseStatus = 4) Then
  660.                     LineOut GetResource("L_MsgErrorText_8") & GetResource("L_MsgErrorText_11")
  661.                 ElseIf ((objProduct.LicenseStatus = 5) And (objProduct.LicenseStatusReason = HR_SL_E_NOT_GENUINE)) Then
  662.                     LineOut GetResource("L_MsgErrorText_8") & GetResource("L_MsgErrorText_12")
  663.                 Else
  664.                     LineOut GetResource("L_MsgActivated_Failed")
  665.                 End If
  666.                 If (iIsPrimaryWindowsSku = 1) Then
  667.                     Exit Sub
  668.                 Else
  669.                     bFoundAtLeastOneKey = TRUE
  670.                 End If
  671.             End If
  672.         Next
  673.     Next
  674.         
  675.     If (bFoundAtLeastOneKey = TRUE) Then
  676.         Exit Sub
  677.     End If
  678.     
  679.     LineOut GetResource("L_MsgErrorProductNotFound")
  680. End Sub
  681.  
  682. Private Sub DisplayAllInformation(strParm, bVerbose)
  683.     Dim objService, objProduct
  684.     Dim strDescription, bKmsClient, strSLActID
  685.     Dim ls, gpMin, gpDay, dwValue, displayDate
  686.     Dim strKms, strPort, strOutput
  687.     Dim KeyManagementServiceTotalRequests
  688.     Dim iIsPrimaryWindowsSku, bUseDefault
  689.     Dim strErr
  690.         
  691.     strParm = LCase(strParm)
  692.  
  693.     For Each objService in g_objWMIService.InstancesOf(ServiceClass)
  694.  
  695.         If bVerbose Then
  696.             LineOut GetResource("L_MsgServiceVersion") & objService.Version
  697.         End If
  698.  
  699.         For Each objProduct in g_objWMIService.InstancesOf(ProductClass)
  700.             If (LCase(objProduct.ApplicationId) = WindowsAppId) Then
  701.                 strSLActID = objProduct.ID
  702.  
  703.                 ' Display information if:
  704.                 '    parm = "all" or
  705.                 '    ActID = parm or
  706.                 '    default to current ActID (parm = "" and IsPrimaryWindowsSKU is 1 or 2)
  707.                 iIsPrimaryWindowsSku = GetIsPrimaryWindowsSKU(objProduct)
  708.                 bUseDefault = False
  709.                 If (strParm ="" And ((iIsPrimaryWindowsSku = 1) Or (iIsPrimaryWindowsSku = 2))) Then
  710.                     bUseDefault = True
  711.                 End If
  712.                 
  713.                 If (strParm = "all") Or (strParm = LCase(strSLActID)) Or (bUseDefault = True) Then
  714.  
  715.                     strDescription = objProduct.Description
  716.                     
  717.                     'If the user didn't specify anything and we are showing the default case, warn them
  718.                     ' if this can't be verified as the primary SKU
  719.                     If ((bUseDefault = True) And (iIsPrimaryWindowsSku = 2)) Then
  720.                         OutputIndeterminateOperationWarning(objProduct)
  721.                     End IF
  722.                     
  723.                     LineOut GetResource("L_MsgProductName") & objProduct.Name
  724.  
  725.                     LineOut GetResource("L_MsgProductDesc") & strDescription
  726.  
  727.                     bKmsClient = IsKmsClient(strDescription)
  728.  
  729.                     If bVerbose Then
  730.                         LineOut GetResource("L_MsgActID") & strSLActID
  731.                         LineOut GetResource("L_MsgAppID") & objProduct.ApplicationID
  732.                         LineOut GetResource("L_MsgPID4") & objProduct.ProductKeyID
  733.                         LineOut GetResource("L_MsgInstallationID") & objProduct.OfflineInstallationId
  734.  
  735.                         If NOT bKmsClient Then
  736.                             LineOut GetResource("L_MsgProcessorCertUrl") & objProduct.ProcessorURL
  737.                             LineOut GetResource("L_MsgMachineCertUrl") & objProduct.MachineURL
  738.                             LineOut GetResource("L_MsgUseLicenseCertUrl") & objProduct.UseLicenseURL
  739.                             LineOut GetResource("L_MsgPKeyCertUrl") & objProduct.ProductKeyURL
  740.                         End If
  741.                     End If
  742.  
  743.                     If objProduct.PartialProductKey <> "" Then
  744.                         LineOut GetResource("L_MsgPartialPKey") & objProduct.PartialProductKey
  745.                     Else
  746.                         LineOut GetResource("L_MsgErrorLicenseNotInUse")
  747.                     End If
  748.  
  749.                     ls = objProduct.LicenseStatus
  750.  
  751.                     If ls = 0 Then
  752.                         LineOut GetResource("L_MsgLicenseStatusUnlicensed_1")
  753.  
  754.                     ElseIf ls = 1 Then
  755.                         LineOut GetResource("L_MsgLicenseStatusLicensed_1")
  756.                         gpMin = objProduct.GracePeriodRemaining
  757.                         If (gpMin <> 0) Then
  758.                             gpDay = Int(gpMin / (24 * 60))
  759.                             strOutput = Replace(GetResource("L_MsgLicenseStatusVL_1"), "%MINUTE%", gpMin)
  760.                             strOutput = Replace(strOutput, "%DAY%", gpDay)
  761.                             LineOut strOutput
  762.                         End If
  763.  
  764.                     ElseIf ls = 2 Then
  765.                         LineOut GetResource("L_MsgLicenseStatusInitialGrace_1")
  766.                         gpMin = objProduct.GracePeriodRemaining
  767.                         gpDay = Int(gpMin / (24 * 60))
  768.                         strOutput = Replace(GetResource("L_MsgLicenseStatusTimeRemaining"), "%MINUTE%", gpMin)
  769.                         strOutput = Replace(strOutput, "%DAY%", gpDay)
  770.                         LineOut strOutput
  771.  
  772.                     ElseIf ls = 3 Then
  773.                         LineOut GetResource("L_MsgLicenseStatusAdditionalGrace_1")
  774.                         gpMin = objProduct.GracePeriodRemaining
  775.                         gpDay = Int(gpMin / (24 * 60))
  776.                         strOutput = Replace(GetResource("L_MsgLicenseStatusTimeRemaining"), "%MINUTE%", gpMin)
  777.                         strOutput = Replace(strOutput, "%DAY%", gpDay)
  778.                         LineOut strOutput
  779.  
  780.                     ElseIf ls = 4 Then
  781.                         LineOut GetResource("L_MsgLicenseStatusNonGenuineGrace_1")
  782.                         gpMin = objProduct.GracePeriodRemaining
  783.                         gpDay = Int(gpMin / (24 * 60))
  784.                         strOutput = Replace(GetResource("L_MsgLicenseStatusTimeRemaining"), "%MINUTE%", gpMin)
  785.                         strOutput = Replace(strOutput, "%DAY%", gpDay)
  786.                         LineOut strOutput
  787.                         
  788.                     ElseIf ls = 5 Then
  789.                         LineOut GetResource("L_MsgLicenseStatusNotification_1")
  790.                         strErr = CStr(Hex(objProduct.LicenseStatusReason))           
  791.                         if (objProduct.LicenseStatusReason = HR_SL_E_NOT_GENUINE) Then
  792.                             strOutput = Replace(GetResource("L_MsgNotificationErrorReasonNonGenuine"), "%ERRCODE%", strErr)
  793.                         ElseIf (objProduct.LicenseStatusReason = HR_SL_E_GRACE_TIME_EXPIRED) Then
  794.                             strOutput = Replace(GetResource("L_MsgNotificationErrorReasonExpiration"), "%ERRCODE%", strErr)
  795.                         Else
  796.                             strOutput = Replace(GetResource("L_MsgNotificationErrorReasonOther"), "%ERRCODE%", strErr)                        
  797.                         End If
  798.                         LineOut strOutput
  799.                        
  800.                     Else
  801.                         LineOut GetResource("L_MsgLicenseStatusUnknown")
  802.                     End If
  803.  
  804.                     If (ls <> 0 And bVerbose) Then
  805.                         Set displayDate = CreateObject("WBemScripting.SWbemDateTime")
  806.                         displayDate.Value = objProduct.EvaluationEndDate
  807.                         If (displayDate.GetFileTime(false) <> 0) Then
  808.                             LineOut GetResource("L_MsgLicenseStatusEvalEndData") & displayDate.GetVarDate
  809.                         End If
  810.                     End If
  811.  
  812.                     '
  813.                     ' KMS client properties
  814.                     '
  815.  
  816.                     If bKmsClient Then
  817.                         LineOut ""
  818.                         LineOut GetResource("L_MsgKmsInfo")
  819.                         LineOut "    " & GetResource("L_MsgCmid") & objService.ClientMachineID
  820.  
  821.                         strKms = objService.KeyManagementServiceMachine
  822.  
  823.                         if Not IsNull(strKms) Then
  824.                             strPort = strGetRegistry(HKEY_LOCAL_MACHINE, SLKeyPath, "KeyManagementServicePort")
  825.                             If (IsNull(strPort) Or strPort = "") Then
  826.                                 strPort = DefaultPort
  827.                             End If
  828.                             LineOut "    " & GetResource("L_MsgRegisteredKmsName") & strKms & ":" & strPort
  829.                         Else
  830.                             strKms = strGetRegistry(HKEY_NETWORK_SERVICE, NSKeyPath, "DiscoveredKeyManagementServiceName")
  831.                             strPort = strGetRegistry(HKEY_NETWORK_SERVICE, NSKeyPath, "DiscoveredKeyManagementServicePort")
  832.                             If IsNull(strKms) Or IsNull(strPort) Then
  833.                                 LineOut "    " & GetResource("L_MsgKmsFromDnsUnavailable")
  834.                             Else
  835.                                 LineOut "    " & GetResource("L_MsgKmsFromDns") & strKms & ":" & strPort
  836.                             End If
  837.                         End If
  838.  
  839.                         LineOut "    " & GetResource("L_MsgKmsPID4") & objService.KeyManagementServiceProductKeyID
  840.                         strOutput = Replace(GetResource("L_MsgActivationInterval"), "%INTERVAL%", objService.VLActivationInterval)
  841.                         LineOut "    " & strOutput
  842.                         strOutput = Replace(GetResource("L_MsgRenewalInterval"), "%INTERVAL%", objService.VLRenewalInterval)
  843.                         LineOut "    " & strOutput
  844.                     End If
  845.  
  846.                     'We should stop processing if we aren't processing All and either we were told to process a single
  847.                     'entry only or we found the primary SKU
  848.                     If strParm <> "all" Then
  849.                         If (strParm = LCase(strSLActID)) Or (iIsPrimaryWindowsSku = 1) Then
  850.                             Exit For  'no need to continue 
  851.                         End If
  852.                     End If
  853.  
  854.                     LineOut ""
  855.                 End If
  856.             End If
  857.         Next
  858.  
  859.         If objService.IsKeyManagementServiceMachine > 0 Then
  860.             LineOut ""
  861.             LineOut GetResource("L_MsgKmsEnabled")
  862.             LineOut "    " & GetResource("L_MsgKmsCurrentCount") & objService.KeyManagementServiceCurrentCount
  863.  
  864.             strValue = strGetRegistry(HKEY_LOCAL_MACHINE, SLKeyPath, "KeyManagementServiceListeningPort")
  865.             If IsNull(strValue) Then
  866.                 LineOut "    " & GetResource("L_MsgKmsListeningOnPort") & DefaultPort
  867.             Else
  868.                 LineOut "    " & GetResource("L_MsgKmsListeningOnPort") & strValue
  869.             End If
  870.  
  871.  
  872.             dwValue = dwGetRegistry(HKEY_LOCAL_MACHINE, SLKeyPath, "DisableDnsPublishing")
  873.             If IsNull(dwValue) Or dwValue = 0 Then
  874.                 LineOut "    " & GetResource("L_MsgKmsDnsPublishingEnabled")
  875.             Else
  876.                 LineOut "    " & GetResource("L_MsgKmsDnsPublishingDisabled")
  877.             End If
  878.  
  879.             dwValue = dwGetRegistry(HKEY_LOCAL_MACHINE, SLKeyPath, "EnableKmsLowPriority")
  880.             If IsNull(dwValue) Or dwValue = 0 Then
  881.                 LineOut "    " & GetResource("L_MsgKmsPriNormal")
  882.             Else
  883.                 LineOut "    " & GetResource("L_MsgKmsPriLow")
  884.             End If
  885.  
  886.             On Error Resume Next
  887.  
  888.             KeyManagementServiceTotalRequests = objService.KeyManagementServiceTotalRequests
  889.             
  890.             If (Not(IsNull(KeyManagementServiceTotalRequests))) And (Not(IsEmpty(KeyManagementServiceTotalRequests))) Then
  891.                 LineOut ""
  892.                 LineOut GetResource("L_MsgKmsCumulativeRequestsFromClients")
  893.                 LineOut "    " & GetResource("L_MsgKmsTotalRequestsRecieved") & objService.KeyManagementServiceTotalRequests
  894.                 LineOut "    " & GetResource("L_MsgKmsFailedRequestsReceived") & objService.KeyManagementServiceFailedRequests
  895.                 LineOut "    " & GetResource("L_MsgKmsRequestsWithStatusUnlicensed") & objService.KeyManagementServiceUnlicensedRequests
  896.                 LineOut "    " & GetResource("L_MsgKmsRequestsWithStatusLicensed") & objService.KeyManagementServiceLicensedRequests
  897.                 LineOut "    " & GetResource("L_MsgKmsRequestsWithStatusInitialGrace") & objService.KeyManagementServiceOOBGraceRequests
  898.                 LineOut "    " & GetResource("L_MsgKmsRequestsWithStatusLicenseExpiredOrHwidOot") & objService.KeyManagementServiceOOTGraceRequests
  899.                 LineOut "    " & GetResource("L_MsgKmsRequestsWithStatusNonGenuineGrace") & objService.KeyManagementServiceNonGenuineGraceRequests
  900.                 LineOut "    " & GetResource("L_MsgKmsRequestsWithStatusNotification") & objService.KeyManagementServiceNotificationRequests
  901.             End If
  902.                         
  903.         End If
  904.     Next
  905. End Sub
  906.  
  907. Private Sub InstallProductKey(strProductKey)
  908.     Dim objService, objProduct
  909.     Dim lRet, strDescription, strOutput
  910.     Dim iIsPrimaryWindowsSku, bIsKMS
  911.  
  912.     bIsKMS = False
  913.     For Each objService in g_objWMIService.InstancesOf(ServiceClass)
  914.         On Error Resume Next
  915.         objService.InstallProductKey(strProductKey)
  916.         QuitIfError()
  917.         For Each objProduct in g_objWMIService.InstancesOf(ProductClass)
  918.             iIsPrimaryWindowsSku = GetIsPrimaryWindowsSKU(objProduct)
  919.             If (iIsPrimaryWindowsSku = 1) Or (iIsPrimaryWindowsSku = 2) Then
  920.                 strDescription = objProduct.Description
  921.                 If (iIsPrimaryWindowsSku = 2) Then
  922.                     OutputIndeterminateOperationWarning(objProduct)
  923.                 End If
  924.                 
  925.                 If IsKmsServer(strDescription) Then
  926.                     ' Set the KMS version in the registry (64 and 32 bit versions)
  927.                     lRet = SetRegistryStr(HKEY_LOCAL_MACHINE, SLKeyPath, "KeyManagementServiceVersion", objService.Version)
  928.                     If (lRet <> 0) Then
  929.                         QuitWithError CStr(Hex(lRet))
  930.                     End If
  931.                     
  932.                     If ExistsRegistryKey(HKEY_LOCAL_MACHINE, SLKeyPath32) Then
  933.                         lRet = SetRegistryStr(HKEY_LOCAL_MACHINE, SLKeyPath32, "KeyManagementServiceVersion", objService.Version)
  934.                         If (lRet <> 0) Then
  935.                             QuitWithError CStr(Hex(lRet))
  936.                         End If
  937.                     End If
  938.                     bIsKMS = True
  939.                 'Only clear the KMS entry if we aren't a KMS.  We may be KMS but have a secondary key from an add-on
  940.                 ElseIf (bIsKMS = False) Then
  941.                     lRet = DeleteRegistryValue(HKEY_LOCAL_MACHINE, SLKeyPath, "KeyManagementServiceVersion")
  942.                     If (lRet <> 0 And lRet <> 2 And lRet <> 5) Then
  943.                         QuitWithError CStr(Hex(lRet))
  944.                     End If
  945.  
  946.                     lRet = DeleteRegistryValue(HKEY_LOCAL_MACHINE, SLKeyPath32, "KeyManagementServiceVersion")
  947.                     If (lRet <> 0 And lRet <> 2 And lRet <> 5) Then
  948.                         QuitWithError CStr(Hex(lRet))
  949.                     End If
  950.                 End If
  951.             End If
  952.         Next
  953.         QuitIfError()
  954.     Next
  955.  
  956.     strOutput = Replace(GetResource("L_MsgInstalledPKey"), "%PKEY%", strProductKey)
  957.     LineOut strOutput
  958. End Sub
  959.  
  960. Private Sub OutputIndeterminateOperationWarning(objProduct)
  961.     Dim strOutput
  962.                     
  963.     LineOut GetResource("L_MsgUndeterminedPrimaryKeyOperation")
  964.     strOutput = Replace(GetResource("L_MsgUndeterminedOperationFormat"), "%PRODUCTDESCRIPTION%", objProduct.Description)
  965.     strOutput = Replace(strOutput, "%PRODUCTID%", objProduct.ID)                    
  966.     LineOut strOutput
  967. End Sub
  968.  
  969. Private Sub ClearPKeyFromRegistry()
  970.     Dim objService
  971.  
  972.     For Each objService in g_objWMIService.InstancesOf(ServiceClass)
  973.         On Error Resume Next
  974.         objService.ClearProductKeyFromRegistry()
  975.         QuitIfError()
  976.     Next
  977.     LineOut GetResource("L_MsgClearedPKey")
  978. End Sub
  979.  
  980. Private Sub InstallLicenseFiles (strParentDirectory, fso)
  981.     Dim file, files, folder, subFolder
  982.  
  983.     Set folder = fso.GetFolder(strParentDirectory)
  984.     Set files = folder.Files
  985.  
  986.     ' Install all license files in folder
  987.     For Each file In files
  988.         If Right(file.Name, 7) = ".xrm-ms" Then
  989.             InstallLicense strParentDirectory & "\" & file.Name
  990.         End If
  991.     Next
  992.  
  993.     For Each subFolder in folder.SubFolders
  994.         InstallLicenseFiles subFolder, fso
  995.     Next
  996. End Sub
  997.  
  998. Private Sub ReinstallLicenses()
  999.     Dim shell, fso, strOemFolder
  1000.     Set shell = WScript.CreateObject("WScript.Shell")
  1001.     Set fso = CreateObject("Scripting.FileSystemObject")
  1002.  
  1003.     strOemFolder = shell.ExpandEnvironmentStrings("%SystemRoot%") & "\system32\oem"
  1004.  
  1005.     LineOut GetResource("L_MsgReinstallingLicenses")
  1006.  
  1007.     InstallLicenseFiles shell.ExpandEnvironmentStrings("%SystemRoot%") & "\system32\licensing", fso
  1008.  
  1009.     If (fso.FolderExists(strOemFolder)) Then
  1010.         InstallLicenseFiles strOemFolder, fso
  1011.     End If
  1012.  
  1013.     LineOut GetResource("L_MsgLicensesReinstalled")
  1014. End Sub
  1015.  
  1016. Private Sub ReArmWindows
  1017.     Dim objService
  1018.  
  1019.     For Each objService in g_objWMIService.InstancesOf(ServiceClass)
  1020.         On Error Resume Next
  1021.         objService.ReArmWindows()
  1022.         QuitIfError()
  1023.     Next
  1024.     LineOut GetResource("L_MsgRearm_1")
  1025.     LineOut GetResource("L_MsgRearm_2")
  1026. End Sub
  1027.  
  1028. Private Sub ExpirationDatime
  1029.     Dim objProduct
  1030.     Dim strSLActID, ls, graceRemaining, strEnds, strOutput
  1031.     Dim iIsPrimaryWindowsSku
  1032.  
  1033.     For Each objProduct in g_objWMIService.InstancesOf(ProductClass)
  1034.         iIsPrimaryWindowsSku = GetIsPrimaryWindowsSKU(objProduct)
  1035.         If (iIsPrimaryWindowsSku = 1) Or (iIsPrimaryWindowsSku = 2) Then
  1036.             strSLActID = objProduct.ID
  1037.             ls      = objProduct.LicenseStatus
  1038.             graceRemaining = objProduct.GracePeriodRemaining
  1039.             strEnds = DateAdd("n", graceRemaining, Now)
  1040.             
  1041.             If (iIsPrimaryWindowsSku = 2) Then
  1042.                 OutputIndeterminateOperationWarning(objProduct)
  1043.             End If
  1044.             
  1045.             If ls = 0 Then
  1046.                 LineOut GetResource("L_MsgLicenseStatusUnlicensed")
  1047.  
  1048.             ElseIf ls = 1 Then
  1049.                 If graceRemaining <> 0 Then
  1050.                     strOutput = Replace(GetResource("L_MsgLicenseStatusVL"), "%ENDDATE%", strEnds)
  1051.                     LineOut strOutput
  1052.                 Else
  1053.                     LineOut GetResource("L_MsgLicenseStatusLicensed")
  1054.                 End If
  1055.  
  1056.             ElseIf ls = 2 Then
  1057.                 strOutput = Replace(GetResource("L_MsgLicenseStatusInitialGrace"), "%ENDDATE%", strEnds)
  1058.                 LineOut strOutput
  1059.  
  1060.             ElseIf ls = 3 Then
  1061.                 strOutput = Replace(GetResource("L_MsgLicenseStatusAdditionalGrace"), "%ENDDATE%", strEnds)
  1062.                 LineOut strOutput
  1063.  
  1064.             ElseIf ls = 4 Then
  1065.                 strOutput = Replace(GetResource("L_MsgLicenseStatusNonGenuineGrace"), "%ENDDATE%", strEnds)
  1066.                 LineOut strOutput
  1067.                 
  1068.             ElseIf ls = 5 Then
  1069.                 LineOut GetResource("L_MsgLicenseStatusNotification")
  1070.                                
  1071.             End If
  1072.         End If
  1073.     Next
  1074. End Sub
  1075.  
  1076. ' volume license service/client management
  1077.  
  1078. Private Sub SetKmsMachineName(strKmsNamePort)
  1079.     Dim objService
  1080.     Dim nColon, strKmsName, strKmsPort, lRet, strOutput
  1081.  
  1082.     nColon = InStr(1, strKmsNamePort, ":")
  1083.     If nColon <> 0 Then
  1084.         strKmsName = Left(strKmsNamePort, nColon - 1)
  1085.         strKmsPort = Right(strKmsNamePort, Len(strKmsNamePort) - nColon)
  1086.     Else
  1087.         strKmsName = strKmsNamePort
  1088.         strKmsPort = ""
  1089.     End If
  1090.  
  1091.     If strKmsName <> "" Then
  1092.         For Each objService in g_objWMIService.InstancesOf(ServiceClass)
  1093.             On Error Resume Next
  1094.             objService.SetKeyManagementServiceMachine(strKmsName)
  1095.             QuitIfError()
  1096.         Next
  1097.     End If
  1098.  
  1099.     On Error Resume Next
  1100.  
  1101.     lRet = SetRegistryStr(HKEY_LOCAL_MACHINE, SLKeyPath, "KeyManagementServicePort", strKmsPort)
  1102.     If (lRet <> 0) Then
  1103.         QuitWithError CStr(Hex(lRet))
  1104.     End If
  1105.  
  1106.     strOutput = Replace(GetResource("L_MsgKmsNameSet"), "%KMS%", strKmsNamePort)
  1107.     LineOut strOutput
  1108. End Sub
  1109.  
  1110. Private Sub ClearKms()
  1111.     Dim objService
  1112.     Dim lRet
  1113.  
  1114.     For Each objService in g_objWMIService.InstancesOf(ServiceClass)
  1115.         On Error Resume Next
  1116.         objService.ClearKeyManagementServiceMachine()
  1117.         If (Err.Number <> HR_S_OK And Err.Number <> HR_ERROR_FILE_NOT_FOUND) Then
  1118.             QuitWithError CStr(Hex(Err.Number))
  1119.         End If
  1120.     Next
  1121.  
  1122.     On Error Resume Next
  1123.  
  1124.     lRet = SetRegistryStr(HKEY_LOCAL_MACHINE, SLKeyPath, "KeyManagementServicePort", DefaultPort)
  1125.     If (lRet <> 0) Then
  1126.         QuitWithError CStr(Hex(lRet))
  1127.     End If
  1128.  
  1129.     LineOut GetResource("L_MsgKmsNameCleared")
  1130. End Sub
  1131.  
  1132. Private Sub SetActivationInterval(intInterval)
  1133.     Dim objService
  1134.     Dim kmsFlag, strOutput
  1135.  
  1136.     If (intInterval < 0) Then
  1137.         LineOut GetResource("L_MsgInvalidDataError")
  1138.         Exit Sub
  1139.     End If
  1140.  
  1141.     For Each objService in g_objWMIService.InstancesOf(ServiceClass)
  1142.         kmsFlag = objService.IsKeyManagementServiceMachine
  1143.         If kmsFlag Then
  1144.             On Error Resume Next
  1145.             objService.SetVLActivationInterval(intInterval)
  1146.             QuitIfError()
  1147.             strOutput = Replace(GetResource("L_MsgActivationSet"), "%ACTIVATION%", intInterval)
  1148.             LineOut strOutput
  1149.             LineOut GetResource("L_MsgWarningKmsReboot")
  1150.         Else
  1151.             LineOut GetResource("L_MsgWarningActivation")
  1152.         End If
  1153.     Next
  1154. End Sub
  1155.  
  1156. Private Sub SetRenewalInterval(intInterval)
  1157.     Dim objService
  1158.     Dim kmsFlag, strOutput
  1159.  
  1160.     If (intInterval < 0) Then
  1161.         LineOut GetResource("L_MsgInvalidDataError")
  1162.         Exit Sub
  1163.     End If
  1164.  
  1165.     For Each objService in g_objWMIService.InstancesOf(ServiceClass)
  1166.         kmsFlag = objService.IsKeyManagementServiceMachine
  1167.         If kmsFlag Then
  1168.             On Error Resume Next
  1169.             objService.SetVLRenewalInterval(intInterval)
  1170.             QuitIfError()
  1171.             strOutput = Replace(GetResource("L_MsgRenewalSet"), "%RENEWAL%", intInterval)
  1172.             LineOut strOutput
  1173.             LineOut GetResource("L_MsgWarningKmsReboot")
  1174.         Else
  1175.             LineOut GetResource("L_MsgWarningRenewal")
  1176.         End If
  1177.     Next
  1178. End Sub
  1179.  
  1180. Private Sub SetKmsListenPort(strPort)
  1181.     Dim objService
  1182.     Dim kmsFlag, strOutput
  1183.  
  1184.     For Each objService in g_objWMIService.InstancesOf(ServiceClass)
  1185.         kmsFlag = objService.IsKeyManagementServiceMachine
  1186.         If kmsFlag Then
  1187.             On Error Resume Next
  1188.             lRet = SetRegistryStr(HKEY_LOCAL_MACHINE, SLKeyPath, "KeyManagementServiceListeningPort", strPort)
  1189.             If (lRet <> 0) Then
  1190.                 QuitWithError CStr(Hex(lRet))
  1191.             End If
  1192.             strOutput = Replace(GetResource("L_MsgKmsPortSet"), "%PORT%", strPort)
  1193.             LineOut strOutput
  1194.             LineOut GetResource("L_MsgWarningKmsReboot")
  1195.         Else
  1196.             LineOut GetResource("L_MsgWarningKmsPort")
  1197.         End If
  1198.     Next
  1199. End Sub
  1200.  
  1201. Private Sub SetDnsPublishingDisabled(bool)
  1202.     Dim objService
  1203.     Dim kmsFlag, lRet, dwValue
  1204.  
  1205.     For Each objService in g_objWMIService.InstancesOf(ServiceClass)
  1206.         kmsFlag = objService.IsKeyManagementServiceMachine
  1207.         If kmsFlag Then
  1208.             On Error Resume Next
  1209.  
  1210.             If bool Then
  1211.                 dwValue = 1
  1212.             Else
  1213.                 dwValue = 0
  1214.             End If
  1215.  
  1216.             lRet = SetRegistryDw(HKEY_LOCAL_MACHINE, SLKeyPath, "DisableDnsPublishing", dwValue)
  1217.             If (lRet <> 0) Then
  1218.                 QuitWithError CStr(Hex(lRet))
  1219.             End If
  1220.  
  1221.             If bool Then
  1222.                 LineOut GetResource("L_MsgKmsDnsPublishingDisabled")
  1223.             Else
  1224.                 LineOut GetResource("L_MsgKmsDnsPublishingEnabled")
  1225.             End If
  1226.             LineOut GetResource("L_MsgWarningKmsReboot")
  1227.         Else
  1228.             LineOut GetResource("L_MsgKmsDnsPublishingWarning")
  1229.         End If
  1230.     Next
  1231. End Sub
  1232.  
  1233. Private Sub SetKmsLowPriority(bool)
  1234.     Dim objService
  1235.     Dim kmsFlag, dwValue
  1236.  
  1237.     For Each objService in g_objWMIService.InstancesOf(ServiceClass)
  1238.         kmsFlag = objService.IsKeyManagementServiceMachine
  1239.         If kmsFlag Then
  1240.             On Error Resume Next
  1241.  
  1242.             If bool Then
  1243.                 dwValue = 1
  1244.             Else
  1245.                 dwValue = 0
  1246.             End If
  1247.  
  1248.             lRet = SetRegistryDw(hKey_LOCAL_MACHINE, SLKeyPath, "EnableKmsLowPriority", dwValue)
  1249.             If (lRet <> 0) Then
  1250.                 QuitWithError CStr(Hex(lRet))
  1251.             End If
  1252.  
  1253.             If bool Then
  1254.                 LineOut GetResource("L_MsgKmsPriSetToLow")
  1255.             Else
  1256.                 LineOut GetResource("L_MsgKmsPriSetToNormal")
  1257.             End If
  1258.             LineOut GetResource("L_MsgWarningKmsReboot")
  1259.         Else
  1260.            LineOut GetResource("L_MsgWarningKmsPri")
  1261.         End If
  1262.     Next
  1263.  
  1264. End Sub
  1265.  
  1266. ' other generic options/helpers
  1267.  
  1268. Private Sub LineOut(str)
  1269.     g_EchoString = g_EchoString & str & vbNewLine
  1270. End Sub
  1271.  
  1272. Private Sub ExitScript(retval)
  1273.     WScript.Echo g_EchoString
  1274.     WScript.Quit retval
  1275. End Sub
  1276.  
  1277. Private Sub InstallLicense(licFile)
  1278.     Dim objService
  1279.     Dim LicenseData
  1280.  
  1281.     On Error Resume Next
  1282.     LicenseData = ReadAllTextFile(licFile)
  1283.     QuitIfError()
  1284.     For Each objService in g_objWMIService.InstancesOf(ServiceClass)
  1285.         objService.InstallLicense(LicenseData)
  1286.         QuitIfError()
  1287.     Next
  1288.     strOutput = Replace(GetResource("L_MsgLicenseFile"), "%LICENSEFILE%", licFile)
  1289.     LineOut strOutput
  1290.     LineOut ""
  1291. End Sub
  1292.  
  1293. ' Returns the encoding for a givven file.
  1294. ' Possible return values: ascii, unicode, unicodeFFFE (big-endian), utf-8
  1295. Function GetFileEncoding(strFileName)
  1296.     Dim strData
  1297.     Dim strEncoding
  1298.     
  1299.     Set oStream = CreateObject("ADODB.Stream")
  1300.         
  1301.     oStream.Type = 1 'adTypeBinary
  1302.     oStream.Open    
  1303.     oStream.LoadFromFile(strFileName)
  1304.     
  1305.     ' Default encoding is ascii
  1306.     strEncoding =  "ascii"
  1307.     
  1308.     strData = BinaryToString(oStream.Read(2))
  1309.     
  1310.     ' Check for little endian (x86) unicode preamble
  1311.     If (Len(strData) = 2) and strData = (Chr(255) + Chr(254)) Then    
  1312.         strEncoding = "unicode"
  1313.     Else        
  1314.         oStream.Position = 0
  1315.         strData = BinaryToString(oStream.Read(3))
  1316.         
  1317.         ' Check for utf-8 preamble
  1318.         If (Len(strData) >= 3) and strData = (Chr(239) + Chr(187) + Chr(191)) Then    
  1319.             strEncoding = "utf-8"
  1320.         End If        
  1321.     End If    
  1322.     
  1323.     oStream.Close
  1324.     
  1325.     GetFileEncoding = strEncoding    
  1326. End Function
  1327.  
  1328. ' Converts binary data (VT_UI1 | VT_ARRAY) to a string (BSTR)
  1329. Function BinaryToString(dataBinary)  
  1330.   Dim i
  1331.   Dim str
  1332.   
  1333.   For i = 1 To LenB(dataBinary)
  1334.     str = str & Chr(AscB(MidB(dataBinary, i, 1)))
  1335.   Next
  1336.   
  1337.   BinaryToString = str
  1338. End Function
  1339.  
  1340. ' Returns string containing the whole text file data. 
  1341. ' Supports ascii, unicode (little-endian) and utf-8 encoding.
  1342. Function ReadAllTextFile(strFileName)
  1343.     Dim strData        
  1344.     Set oStream = CreateObject("ADODB.Stream")        
  1345.         
  1346.     oStream.Type = 2 'adTypeText
  1347.     oStream.Open
  1348.     oStream.Charset = GetFileEncoding(strFileName)
  1349.     oStream.LoadFromFile(strFileName)
  1350.             
  1351.     strData = oStream.ReadText(-1) 'adReadAll
  1352.     
  1353.     oStream.Close
  1354.    
  1355.     ReadAllTextFile = strData
  1356. End Function
  1357.  
  1358.  
  1359. Private Function HandleOptionParam(bShowKmsInfo, bShowKmsClientInfo, cParam, mustProvide, opt, param)
  1360.     Dim strOutput
  1361.  
  1362.     HandleOptionParam = True
  1363.     If WScript.Arguments.Count <= cParam Then
  1364.         HandleOptionParam = False
  1365.         If mustProvide Then
  1366.             LineOut ""
  1367.             strOutput = Replace(GetResource("L_MsgErrorText_9"), "%OPTION%", opt)
  1368.             strOutput = Replace(strOutput, "%PARAM%", param)
  1369.             LineOut strOutput
  1370.             Call DisplayUsage(bShowKmsInfo, bShowKmsClientInfo)
  1371.         End If
  1372.     End If
  1373. End Function
  1374.  
  1375. Private Sub ShowErrorNum(strMessage, strErrNum)
  1376.     Dim strOutput
  1377.  
  1378.     Select Case strErrNum
  1379.         Case "5":
  1380.             strErrText = GetResource("L_MsgErrorText_1")
  1381.         Case "80070005":
  1382.             strErrText = GetResource("L_MsgErrorText_1")
  1383.         Case "C004F025":
  1384.             strErrText = GetResource("L_MsgErrorText_1")
  1385.         Case "8007232A":
  1386.             strErrText = GetResource("L_MsgErrorText_2")
  1387.         Case "C004F012":
  1388.             strErrText = GetResource("L_MsgErrorText_3")
  1389.         Case "C004F038":
  1390.             strErrText = GetResource("L_MsgErrorText_4")
  1391.         Case "C004F039":
  1392.             strErrText = GetResource("L_MsgErrorText_5")
  1393.         Case "C004D307":
  1394.             strErrText = GetResource("L_MsgErrorText_10")
  1395.         Case Else
  1396.             strOutput = Replace(GetResource("L_MsgErrorText_6"), "%ERRCODE%", strErrNum)
  1397.             LineOut strOutput
  1398.     End Select
  1399.  
  1400.     LineOut strMessage & "0x" & strErrNum & " " & strErrText
  1401. End Sub
  1402.  
  1403. Private Sub QuitIfError()
  1404.     If Err.Number <> 0 Then
  1405.         ShowErrorNum GetResource("L_MsgErrorText_8"), Hex(Err.Number)
  1406.         ExitScript 1
  1407.     End If
  1408. End Sub
  1409.  
  1410. Private Sub QuitWithError(strErrNum)
  1411.     ShowErrorNum GetResource("L_MsgErrorText_8"), strErrNum
  1412.     ExitScript 1
  1413. End Sub
  1414.  
  1415. Private Function booleanConnect()
  1416.  
  1417.     On Error Resume Next
  1418.  
  1419.     Dim objLocator, strOutput
  1420.     Dim objServer
  1421.     Dim objProcServer, objProc
  1422.     Dim strErr
  1423.  
  1424.     booleanConnect = True     'There is no error.
  1425.  
  1426.     'If this is the local computer, set everything and return immediately
  1427.     If g_strComputer = "." Then
  1428.         Set g_objWMIService = GetObject("winmgmts:\\" & g_strComputer & "\root\cimv2")
  1429.         Set g_objRegistry = GetObject("winmgmts:\\" & g_strComputer & "\root\default:StdRegProv")
  1430.  
  1431.         Set objProc = GetObject("winmgmts:\\" & g_strComputer & "\root\cimv2:Win32_Processor='cpu0'")
  1432.         strErr = CStr(Hex(Err.Number))
  1433.         If Err.Number <> 0 Then
  1434.             strOutput = Replace(GetResource("L_MsgErrorConnectionProcessor"), "%ERRCODE%", strErr)
  1435.             strOutput = Replace(strOutput, "%COMPUTERNAME%", g_strComputer)
  1436.             LineOut strOutput
  1437.             If Err.Description <> "" Then
  1438.                 LineOut GetResource("L_MsgErrorDescription") & Err.Description & "."
  1439.             End If
  1440.             Err.Clear
  1441.             booleanConnect = False     'An error occurred
  1442.             Exit Function
  1443.         End If
  1444.         GetProcessorArchitecture(objProc)
  1445.         
  1446.         If Not g_serviceConnected Then
  1447.             g_serviceConnected = True
  1448.         End If
  1449.         Exit Function
  1450.     End If
  1451.  
  1452.     'Otherwise, establish the remote object connections
  1453.  
  1454.     ' Create Locator object to connect to remote CIM object manager
  1455.     Set objLocator = CreateObject("WbemScripting.SWbemLocator")
  1456.     strErr = CStr(Hex(Err.Number))
  1457.     If Err.Number <> 0 Then
  1458.         strOutput = Replace(GetResource("L_MsgErrorWMI"), "%ERRCODE%", strErr)
  1459.         LineOut strOutput
  1460.         If Err.Description <> "" Then
  1461.             LineOut GetResource("L_MsgErrorDescription") & Err.Description & "."
  1462.         End If
  1463.         Err.Clear
  1464.         booleanConnect = False     'An error occurred
  1465.         Exit Function
  1466.     End If
  1467.  
  1468.     ' Connect to the namespace which is either local or remote
  1469.     Set g_objWMIService = objLocator.ConnectServer (g_strComputer, "\root\cimv2", g_strUserName, g_strPassword)
  1470.     strErr = CStr(Hex(Err.Number))
  1471.     If Err.Number <> 0 Then
  1472.         strOutput = Replace(GetResource("L_MsgErrorConnection"), "%ERRCODE%", strErr)
  1473.         strOutput = Replace(strOutput, "%COMPUTERNAME%", g_strComputer)
  1474.         LineOut strOutput
  1475.         If Err.Description <> "" Then
  1476.             LineOut GetResource("L_MsgErrorDescription") & Err.Description & "."
  1477.         End If
  1478.         Err.Clear
  1479.         booleanConnect = False     'An error occurred
  1480.         Exit Function
  1481.     End If
  1482.  
  1483.     g_objWMIService.Security_.impersonationlevel = 3
  1484.     strErr = CStr(Hex(Err.Number))
  1485.     If Err.Number <> 0 Then
  1486.         strOutput = Replace(GetResource("L_MsgErrorImpersonation"), "%ERRCODE%", strErr)
  1487.         LineOut strOutput
  1488.         If Err.Description <> "" Then
  1489.             LineOut GetResource("L_MsgErrorDescription") & Err.Description & "."
  1490.         End If
  1491.         Err.Clear
  1492.         booleanConnect = False     'An error occurred
  1493.         Exit Function
  1494.     End If
  1495.  
  1496.     Set objServer = objLocator.ConnectServer(g_strComputer, "\root\default:StdRegProv", g_strUserName, g_strPassword)
  1497.     strErr = CStr(Hex(Err.Number))
  1498.     If Err.Number <> 0 Then
  1499.         strOutput = Replace(GetResource("L_MsgErrorConnectionRegistry"), "%ERRCODE%", strErr)
  1500.         strOutput = Replace(strOutput, "%COMPUTERNAME%", g_strComputer)
  1501.         LineOut strOutput
  1502.         If Err.Description <> "" Then
  1503.             LineOut GetResource("L_MsgErrorDescription") & Err.Description & "."
  1504.         End If
  1505.         Err.Clear
  1506.         booleanConnect = False     'An error occurred
  1507.         Exit Function
  1508.     End If
  1509.  
  1510.     objServer.Security_.ImpersonationLevel = 3
  1511.     Set g_objRegistry = objServer.Get("StdRegProv")
  1512.     strErr = CStr(Hex(Err.Number))
  1513.     If Err.Number <> 0 Then
  1514.         strOutput = Replace(GetResource("L_MsgErrorConnectionRegistry"), "%ERRCODE%", strErr)
  1515.         strOutput = Replace(strOutput, "%COMPUTERNAME%", g_strComputer)
  1516.         LineOut strOutput
  1517.         If Err.Description <> "" Then
  1518.             LineOut GetResource("L_MsgErrorDescription") & Err.Description & "."
  1519.         End If
  1520.         Err.Clear
  1521.         booleanConnect = False     'An error occurred
  1522.         Exit Function
  1523.     End If
  1524.     
  1525.     Set objProcServer = objLocator.ConnectServer(g_strComputer, "\root\cimv2:Win32_Processor='cpu0'", g_strUserName, g_strPassword)
  1526.     strErr = CStr(Hex(Err.Number))
  1527.     If Err.Number <> 0 Then
  1528.         strOutput = Replace(GetResource("L_MsgErrorConnectionProcessor"), "%ERRCODE%", strErr)
  1529.         strOutput = Replace(strOutput, "%COMPUTERNAME%", g_strComputer)
  1530.         LineOut strOutput
  1531.         If Err.Description <> "" Then
  1532.             LineOut GetResource("L_MsgErrorDescription") & Err.Description & "."
  1533.         End If
  1534.         Err.Clear
  1535.         booleanConnect = False     'An error occurred
  1536.         Exit Function
  1537.     End If
  1538.     Set objProc = objProcServer.Get("Win32_Processor='cpu0'")
  1539.     strErr = CStr(Hex(Err.Number))
  1540.     If Err.Number <> 0 Then
  1541.         strOutput = Replace(GetResource("L_MsgErrorConnectionProcessor"), "%ERRCODE%", strErr)
  1542.         strOutput = Replace(strOutput, "%COMPUTERNAME%", g_strComputer)
  1543.         LineOut strOutput
  1544.         If Err.Description <> "" Then
  1545.             LineOut GetResource("L_MsgErrorDescription") & Err.Description & "."
  1546.         End If
  1547.         Err.Clear
  1548.         booleanConnect = False     'An error occurred
  1549.         Exit Function
  1550.     End If
  1551.     GetProcessorArchitecture(objProc)
  1552.     
  1553.     If Not g_serviceConnected Then
  1554.         g_serviceConnected = True
  1555.     End If
  1556. End Function
  1557.  
  1558. Private Function IsKmsClient(strDescription)
  1559.     If InStr(strDescription, "VOLUME_KMSCLIENT") > 0 Then
  1560.         IsKmsClient = True
  1561.     Else
  1562.         IsKmsClient = False
  1563.     End If
  1564. End Function
  1565.  
  1566. Private Function IsKmsServer(strDescription)
  1567.     If IsKmsClient(strDescription) Then
  1568.         IsKmsServer = False
  1569.     Else
  1570.         If InStr(strDescription, "VOLUME_KMS") > 0 Then
  1571.             IsKmsServer = True
  1572.         Else
  1573.             IsKmsServer = False
  1574.         End If
  1575.     End If
  1576. End Function
  1577.  
  1578. 'Returns 0 if this is not the primary SKU, 1 if it is, and 2 if we aren't certain (older clients)
  1579. Function GetIsPrimaryWindowsSKU(objProduct)
  1580.     Dim iPrimarySku
  1581.     Dim bIsAddOn
  1582.     
  1583.     'Assume this is not the primary SKU
  1584.     iPrimarySku = 0
  1585.     'Verify the license is for Windows, that it has a partial key, and that 
  1586.     If (LCase(objProduct.ApplicationId) = WindowsAppId And objProduct.PartialProductKey <> "") Then
  1587.         'If we can get verify the AddOn property then we can be certain
  1588.         On Error Resume Next
  1589.         bIsAddOn = objProduct.LicenseIsAddon
  1590.         If Err.Number = 0 Then
  1591.             If bIsAddOn = true Then
  1592.                 iPrimarySku = 0
  1593.             Else
  1594.                 iPrimarySku = 1
  1595.             End If            
  1596.         Else
  1597.             'If we can not get the AddOn property then we assume this is a previous version
  1598.             'and we return a value of Uncertain, unless we can prove otherwise
  1599.             If (IsKmsClient(objProduct.Description) Or IsKmsServer(objProduct.Description)) Then
  1600.                 'If the description is KMS related, we can be certain that this is a primary SKU
  1601.                 iPrimarySku = 1
  1602.             Else
  1603.                 'Indeterminate since the property was missing and we can't verify KMS
  1604.                 iPrimarySku = 2
  1605.             End If
  1606.         End If
  1607.     End If
  1608.     GetIsPrimaryWindowsSKU = iPrimarySku
  1609. End Function
  1610.  
  1611. Private Function WasPrimaryKeyFound(strPrimarySkuType)
  1612.     If (IsKmsServer(strPrimarySkuType) Or IsKmsClient(strPrimarySkuType) Or (InStr(strPrimarySkuType, NonKMSPrimaryKey) > 0) Or (InStr(strPrimarySkuType, IndeterminatePrimaryKeyFound) > 0)) Then
  1613.         WasPrimaryKeyFound = True
  1614.     Else
  1615.         WasPrimaryKeyFound = False
  1616.     End If
  1617. End Function
  1618.  
  1619.  
  1620. Private Function CanPrimaryKeyTypeBeDetermined(strPrimarySkuType)
  1621.     If ((InStr(strPrimarySkuType, IndeterminatePrimaryKeyFound) > 0) Or (InStr(strPrimarySkuType, NoPrimaryKeyFound) > 0)) Then
  1622.         CanPrimaryKeyTypeBeDetermined = False
  1623.     Else
  1624.         CanPrimaryKeyTypeBeDetermined = True
  1625.     End If
  1626. End Function
  1627.  
  1628.  
  1629. Private Function GetPrimarySKUType()
  1630.     Dim objService, objProduct
  1631.     Dim strPrimarySKUType, strDescription
  1632.     Dim iIsPrimaryWindowsSku    
  1633.     
  1634.     For Each objService in g_objWMIService.InstancesOf(ServiceClass)
  1635.         For Each objProduct in g_objWMIService.InstancesOf(ProductClass)
  1636.             iIsPrimaryWindowsSku = GetIsPrimaryWindowsSKU(objProduct)
  1637.             If (iIsPrimaryWindowsSku = 1) Then
  1638.                 strDescription = objProduct.Description
  1639.                 If (IsKmsServer(strDescription) Or IsKmsClient(strDescription)) Then
  1640.                     strPrimarySKUType = strDescription
  1641.                 Else
  1642.                     strPrimarySKUType = NonKMSPrimaryKey
  1643.                 End If
  1644.                 Exit For  'no need to continue
  1645.             ElseIf ((iIsPrimaryWindowsSku = 2) And strPrimarySKUType = "") Then
  1646.                 strPrimarySKUType = IndeterminatePrimaryKeyFound
  1647.             End If
  1648.         Next
  1649.     Next
  1650.     If strPrimarySKUType = "" Then
  1651.         strPrimarySKUType = NoPrimaryKeyFound
  1652.     End If
  1653.     
  1654.     GetPrimarySKUType = strPrimarySKUType
  1655. End Function
  1656.  
  1657. ' Registry operations
  1658.  
  1659. Private Function dwGetRegistry(hKey, strKeyPath, strValueName)
  1660.     g_objRegistry.GetDwordValue hKey, strKeyPath, strValueName, dwGetRegistry
  1661. End Function
  1662.  
  1663. Private Function strGetRegistry(hKey, strKeyPath, strValueName)
  1664.     g_objRegistry.GetStringValue hKey, strKeyPath, strValueName, strGetRegistry
  1665. End Function
  1666.  
  1667. Private Function SetRegistryDw(hKey, strKeyPath, strValueName, dwValue)
  1668.     SetRegistryDw = g_objRegistry.SetDwordValue(hKey, strKeyPath, strValueName, dwValue)
  1669. End Function
  1670.  
  1671. Private Function SetRegistryStr(hKey, strKeyPath, strValueName, strValue)
  1672.     SetRegistryStr = g_objRegistry.SetStringValue(hKey, strKeyPath, strValueName, strValue)
  1673. End Function
  1674.  
  1675. Private Function DeleteRegistryValue(hKey, strKeyPath, strValueName)
  1676.     DeleteRegistryValue = g_objRegistry.DeleteValue(hKey, strKeyPath, strValueName)
  1677. End Function
  1678.  
  1679. Private Function ExistsRegistryKey(hKey, strKeyPath)
  1680.     Dim bGranted
  1681.     Dim lRet
  1682.  
  1683.     ' Check for KEY_QUERY_VALUE for this key
  1684.     lRet = g_objRegistry.CheckAccess(hKey, strKeyPath, 1, bGranted)
  1685.  
  1686.     ' Ignore real access rights, just look for existence of the key
  1687.     If lRet<>2 Then
  1688.         ExistsRegistryKey = True
  1689.     Else
  1690.         ExistsRegistryKey = False
  1691.     End If
  1692. End Function
  1693.  
  1694. ' Resource manipulation
  1695.  
  1696. ' Get the resource string with the given name from the locale specific
  1697. ' dictionary. If not found, use the built-in default.
  1698. Private Function GetResource(name)
  1699.     LoadResourceData
  1700.     If g_resourceDictionary.Exists(name) Then
  1701.         GetResource = g_resourceDictionary.Item(name)
  1702.     Else
  1703.         GetResource = Eval(name)
  1704.     End If
  1705. End Function
  1706.  
  1707. ' Loads resource strings from an ini file of the appropriate locale
  1708. Private Function LoadResourceData
  1709.     If g_resourcesLoaded Then
  1710.         Exit Function
  1711.     End If
  1712.  
  1713.     Dim lang, value, ini
  1714.     Dim fso
  1715.     Set fso = WScript.CreateObject("Scripting.FileSystemObject")
  1716.  
  1717.     On Error Resume Next
  1718.     lang = GetUILanguage()
  1719.     If Err.Number <> 0 Then
  1720.         'API does not exist prior to Vista so no resources to load
  1721.         g_resourcesLoaded = True
  1722.         Exit Function
  1723.     End If
  1724.  
  1725.     ini = fso.GetParentFolderName(WScript.ScriptFullName) & "\slmgr\" _
  1726.         & ToHex(lang) & "\" & fso.GetBaseName(WScript.ScriptName) &  ".ini"
  1727.  
  1728.     If fso.FileExists(ini) Then
  1729.         Dim stream, file
  1730.         Const ForReading = 1, TristateTrue = -1 'Read file in unicode format
  1731.  
  1732.         Set stream = fso.OpenTextFile(ini, ForReading, False, TristateTrue)
  1733.         ReadResources(stream)
  1734.        stream.Close
  1735.     End If
  1736.  
  1737.     g_resourcesLoaded = True
  1738. End Function
  1739.  
  1740. ' Reads resource strings from an ini file
  1741. Private Function ReadResources(stream)
  1742.     const ERROR_FILE_NOT_FOUND = 2
  1743.     Dim ln, arr, key, value
  1744.  
  1745.     If Not IsObject(stream) Then Err.Raise ERROR_FILE_NOT_FOUND
  1746.  
  1747.     Do Until stream.AtEndOfStream
  1748.         ln = stream.ReadLine
  1749.  
  1750.         arr = Split(ln, "=", 2, 1)
  1751.         If UBound(arr, 1) = 1 Then
  1752.             ' Trim the key and the value first before trimming quotes
  1753.             key = Trim(arr(0))
  1754.             value = TrimChar(Trim(arr(1)), """")
  1755.  
  1756.             If key <> "" Then
  1757.                 g_resourceDictionary.Add key, value
  1758.             End If
  1759.         End If
  1760.     Loop
  1761. End Function
  1762.  
  1763. ' Trim a character from the text string
  1764. Private Function TrimChar(s, c)
  1765.     Const vbTextCompare = 1
  1766.  
  1767.     ' Trim character from the start
  1768.     If InStr(1, s, c, vbTextCompare) = 1 Then
  1769.         s = Mid(s, 2)
  1770.     End If
  1771.         
  1772.     ' Trim character from the end
  1773.     If InStr(Len(s), s, c, vbTextCompare) = Len(s) Then
  1774.         s = Mid(s, 1, Len(s) - 1)
  1775.     End If
  1776.  
  1777.     TrimChar = s
  1778. End Function
  1779.  
  1780. ' Get a 4-digit hexadecimal number
  1781. Private Function ToHex(n)
  1782.     Dim s : s = Hex(n)
  1783.     ToHex = String(4 - Len(s), "0") & s
  1784. End Function
  1785.