Share via


Renommer la méthode de la classe Win32_ComputerSystem

La méthode Rename renomme un ordinateur.

Cette rubrique utilise la syntaxe MOF (Managed Object Format). Pour plus d’informations sur l’utilisation de cette méthode, consultez Appel d’une méthode.

Syntaxe

uint32 Rename(
  [in] string Name,
  [in] string Password,
  [in] string UserName
);

Paramètres

Nom [in]

Nouveau nom d’ordinateur. La valeur de ce paramètre ne peut pas inclure des caractères de contrôle, des espaces de début ou de fin, ou l’un des caractères suivants : / \\ [ ].

Mot de passe [in]

Mot de passe à utiliser lors de la connexion au contrôleur de domaine si le paramètre UserName spécifie un nom de compte. Sinon, ce paramètre doit être NULL. Pour plus d’informations sur les paramètres Password et UserName , consultez la section Remarques de cette rubrique.

UserName [in]

Chaîne qui spécifie le nom de compte à utiliser lors de la connexion au contrôleur de domaine. La chaîne doit être terminée par null et doit spécifier un nom netBIOS de domaine et un compte d’utilisateur, par exemple, « DOMAINNAME\username » ou «someone@domainname.com », qui est un nom d’utilisateur principal (UPN). Si le paramètre UserName a la valeur NULL, WMI utilise le contexte de l’appelant. Pour plus d’informations sur les paramètres Password et UserName , consultez la section Remarques de cette rubrique.

Valeur retournée

Retourne un 0 (zéro) en cas de réussite. Une valeur de retour différente de zéro indique une erreur. En cas de réussite, un redémarrage est nécessaire. Pour obtenir des codes d’erreur supplémentaires, consultez Constantes d’erreur WMI ou WbemErrorEnum. Pour connaître les valeurs HRESULT générales, consultez Codes d’erreur système.

Réussite (0)

Autre (1 4294967295)

Notes

Vous pouvez utiliser la méthode Rename pour renommer un ordinateur si vous êtes membre du groupe d’administrateurs locaux. Toutefois, vous ne pouvez pas utiliser la méthode à distance pour les ordinateurs de domaine.

Si les paramètres Password et UserName sont spécifiés, la connexion à WMI doit utiliser le niveau d’authentification RPC_C_AUTHN_LEVEL_PKT_PRIVACY (wbemAuthenticationLevelPktPrivacy pour le script et Visual Basic (VB)).

Pour vous connecter à un ordinateur distant et spécifier des informations d’identification, utilisez la connexion à l’objet localisateur, qui est IWbemLocator pour C++, et SWbemLocator pour script et VB. N’utilisez pas la connexion moniker.

Pour vous connecter à un ordinateur local, vous ne pouvez pas spécifier un mot de passe ou une autorité d’authentification, telle que Kerberos. Vous pouvez uniquement spécifier le mot de passe et l’autorité dans les connexions aux ordinateurs distants.

Si le niveau d’authentification est trop faible quand un mot de passe et un nom d’utilisateur sont spécifiés, WMI retourne l’erreur WBEM_E_ENCRYPTED_CONNECTION_REQUIRED pour C/C++, et wbemErrEncryptedConnectionRequired pour le script et VB.

Pour plus d’informations, consultez SWbemLocator_ConnectServer,IWbemLocator::ConnectServer et Construction d’une chaîne Moniker.

Exemples

Le script suivant vous montre comment renommer un ordinateur local.

Name = "name"
Password = "password"
Username = "username"

Set objWMIService = GetObject("Winmgmts:root\cimv2")

' Call always gets only one Win32_ComputerSystem object.
For Each objComputer in _
    objWMIService.InstancesOf("Win32_ComputerSystem")

        Return = objComputer.rename(Name,Password,Username)
        If Return <> 0 Then
           WScript.Echo "Rename failed. Error = " & Err.Number
        Else
           WScript.Echo "Rename succeeded." & _
               " Reboot for new name to go into effect"
        End If

Next

L’exemple de code C++ suivant renomme un système informatique.

int set_computer_name(const string &newname/*, const string &username, const string &password*/)
{
 HRESULT hres;


// Step 1: --------------------------------------------------
 // Initialize COM. ------------------------------------------


hres = CoInitializeEx(0, COINIT_MULTITHREADED); 
 if (FAILED(hres))
 {
 cout << "Failed to initialize COM library. Error code = 0x" 
 << hex << hres << endl;
 return 1; // Program has failed.
 }


// Step 2: --------------------------------------------------
 // Set general COM security levels --------------------------
 // Note: If you are using Windows 2000, you need to specify -
 // the default authentication credentials for a user by using
 // a SOLE_AUTHENTICATION_LIST structure in the pAuthList ----
 // parameter of CoInitializeSecurity ------------------------


hres = CoInitializeSecurity(
 NULL, 
 -1, // COM authentication
 NULL, // Authentication services
 NULL, // Reserved
 RPC_C_AUTHN_LEVEL_DEFAULT, // Default authentication 
 RPC_C_IMP_LEVEL_IMPERSONATE, // Default Impersonation 
 NULL, // Authentication info
 EOAC_NONE, // Additional capabilities 
 NULL // Reserved
 );




 if (FAILED(hres))
 {
 cout << "Failed to initialize security. Error code = 0x" 
 << hex << hres << endl;
 CoUninitialize();
 return 1; // Program has failed.
 }

 // Step 3: ---------------------------------------------------
 // Obtain the initial locator to WMI -------------------------


IWbemLocator *pLoc = NULL;


hres = CoCreateInstance(
 CLSID_WbemLocator, 
 0, 
 CLSCTX_INPROC_SERVER, 
 IID_IWbemLocator, (LPVOID *) &pLoc);

 if (FAILED(hres))
 {
 cout << "Failed to create IWbemLocator object."
 << " Err code = 0x"
 << hex << hres << endl;
 CoUninitialize();
 return 1; // Program has failed.
 }


// Step 4: -----------------------------------------------------
 // Connect to WMI through the IWbemLocator::ConnectServer method


IWbemServices *pSvc = NULL;

 // Connect to the root\cimv2 namespace with
 // the current user and obtain pointer pSvc
 // to make IWbemServices calls.
 hres = pLoc->ConnectServer(
 _bstr_t(L"ROOT\\CIMV2"), // Object path of WMI namespace
 NULL, // User name. NULL = current user
 NULL, // User password. NULL = current
 0, // Locale. NULL indicates current
 NULL, // Security flags.
 0, // Authority (e.g. Kerberos)
 0, // Context object 
 &pSvc // pointer to IWbemServices proxy
 );

 if (FAILED(hres))
 {
 cout << "Could not connect. Error code = 0x" 
 << hex << hres << endl;
 pLoc->Release(); 
 CoUninitialize();
 return 1; // Program has failed.
 }


/*cout << "Connected to ROOT\\CIMV2 WMI namespace" << endl;*/




 // Step 5: --------------------------------------------------
 // Set security levels on the proxy -------------------------


hres = CoSetProxyBlanket(
 pSvc, // Indicates the proxy to set
 RPC_C_AUTHN_WINNT, // RPC_C_AUTHN_xxx
 RPC_C_AUTHZ_NONE, // RPC_C_AUTHZ_xxx
 NULL, // Server principal name 
 RPC_C_AUTHN_LEVEL_CALL, // RPC_C_AUTHN_LEVEL_xxx 
 RPC_C_IMP_LEVEL_IMPERSONATE, // RPC_C_IMP_LEVEL_xxx
 NULL, // client identity
 EOAC_NONE // proxy capabilities 
 );


if (FAILED(hres))
 {
 cout << "Could not set proxy blanket. Error code = 0x" 
 << hex << hres << endl;
 pSvc->Release();
 pLoc->Release(); 
 CoUninitialize();
 return 1; // Program has failed.
 }


// Step 6: --------------------------------------------------
 // Use the IWbemServices pointer to make requests of WMI ----


// For example, get the name of the operating system
 IEnumWbemClassObject* pEnumerator = NULL;
 hres = pSvc->ExecQuery(
 bstr_t("WQL"), 
 bstr_t("SELECT * FROM Win32_ComputerSystem"),
 WBEM_FLAG_FORWARD_ONLY | WBEM_FLAG_RETURN_IMMEDIATELY, 
 NULL,
 &pEnumerator);

 if (FAILED(hres))
 {
 cout << "Query for operating system name failed."
 << " Error code = 0x" 
 << hex << hres << endl;
 pSvc->Release();
 pLoc->Release();
 CoUninitialize();
 return 1; // Program has failed.
 }


// Step 7: -------------------------------------------------
 // Get the data from the query in step 6 -------------------

 IWbemClassObject *pclsObj;
 ULONG uReturn = 0;

 while (pEnumerator)
 {
 HRESULT hr = pEnumerator->Next(WBEM_INFINITE, 1, 
 &pclsObj, &uReturn);


if(0 == uReturn)
 {
 break;
 }


// set up to call the Win32_ComputerSystem::Rename method
 BSTR MethodName = SysAllocString(L"Rename");
 BSTR ClassName = SysAllocString(L"Win32_ComputerSystem");


IWbemClassObject* pClass = NULL;
 hres = pSvc->GetObject(ClassName, 0, NULL, &pClass, NULL);


IWbemClassObject* pInParamsDefinition = NULL;
 hres = pClass->GetMethod(MethodName, 0, 
 &pInParamsDefinition, NULL);


IWbemClassObject* pClassInstance = NULL;
 hres = pInParamsDefinition->SpawnInstance(0, &pClassInstance);


// Create the values for the in parameters
 wstring val;
 BSTR NewName;
 val.assign(newname.begin(), newname.end());
 NewName = SysAllocString(val.c_str());


VARIANT varName;
 varName.vt = VT_BSTR;
 varName.bstrVal = NewName;


// Store the value for the in parameters
 hres = pClassInstance->Put(L"Name", 0,
 &varName, 0);
 wprintf(L"Set computer name to %s\n", V_BSTR(&varName));


VARIANT var;
 CIMTYPE pType;
 LONG pFlavor;
 pclsObj->Get(L"__PATH",0,&var,&pType,&pFlavor);


// Execute Method
 IWbemClassObject* pOutParams = NULL;
 hres = pSvc->ExecMethod(var.bstrVal, MethodName, 0,
 NULL, pClassInstance, &pOutParams, NULL);


if (FAILED(hres))
 {
 cout << "Could not execute method. Error code = 0x" 
 << hex << hres << endl;
 VariantClear(&varName);
 SysFreeString(ClassName);
 SysFreeString(MethodName);
 SysFreeString(NewName);
 pClass->Release();
 pInParamsDefinition->Release();
 pOutParams->Release();
 return 1; // Program has failed.
 }


// To see what the method returned,
 // use the following code. The return value will
 // be in &varReturnValue
 VARIANT varReturnValue;
 hres = pOutParams->Get(_bstr_t(L"ReturnValue"), 0, 
 &varReturnValue, NULL, 0);




 // Clean up
 //--------------------------
 VariantClear(&varName);
 VariantClear(&varReturnValue);
 SysFreeString(ClassName);
 SysFreeString(MethodName);
 SysFreeString(NewName);
 pClass->Release();
 pInParamsDefinition->Release();
 pOutParams->Release();
 return 0;


}


// Cleanup
 // ========

 pSvc->Release();
 pLoc->Release();
 pEnumerator->Release();
 pclsObj->Release();
 CoUninitialize();


return 0; // Program successfully completed.

Spécifications

Condition requise Valeur
Client minimal pris en charge
Windows Vista
Serveur minimal pris en charge
Windows Server 2008
Espace de noms
Racine\CIMV2
MOF
CIMWin32.mof
DLL
CIMWin32.dll

Voir aussi

Win32_ComputerSystem

Tâches WMI : Comptes et domaines