Win32_Process 類別的 Terminate 方法

TerminateWMI 類別方法會終止進程及其所有線程。

本主題使用 Managed 物件格式 (MOF) 語法。 如需使用此方法的詳細資訊,請參閱 呼叫方法

語法

uint32 Terminate(
  [in] uint32 Reason
);

參數

原因 [in]

結束進程的程式碼,以及因呼叫而終止之所有線程的程式碼。

傳回值

如果進程成功終止,則傳回值為 0 (零) ,以及指出錯誤的任何其他數位。 如需其他錯誤碼,請參閱 WMI 錯誤常數WbemErrorEnum。 如需一般 HRESULT 值,請參閱 系統錯誤碼

成功完成 (0)

拒絕存取 (2)

許可權不足 (3)

未知的失敗 (8)

(9) 找不到路徑

不正確參數 (21)

其他 (22 4294967295)

備註

概觀

電腦問題通常是因為不再如預期般運作的程式所造成。 例如,進程可能會流失記憶體,或可能已停止回應使用者輸入。 發生這類問題時,進程必須終止。 雖然這似乎很簡單,但終止程式可能會因為數個因素而複雜:

  • 進程可能會無回應,因此不再回應關閉應用程式的功能表或鍵盤命令。 這讓一般使用者無法關閉應用程式並終止進程。
  • 此程式可能會被遺棄。 例如,腳本可能會建立 Word 的實例,然後結束而不終結該實例。 實際上,即使看不到任何使用者介面,Word 仍會在電腦上執行。 因為沒有使用者介面,所以沒有功能表或鍵盤命令可用來終止進程。
  • 您可能不知道需要終止哪個進程。 例如,您可能想要終止超過指定記憶體數量的所有程式。
  • 因為工作管理員只允許您終止您所建立的進程,所以即使您是電腦上的系統管理員,您也可能無法終止進程。

腳本可讓您克服所有這些潛在障礙,讓您對電腦進行大量系統管理控制。 例如,如果您懷疑使用者正在執行組織中已禁止的遊戲,您可以輕鬆地撰寫腳本以連線到每部電腦、識別遊戲是否正在執行,以及立即終止程式。

使用 Terminate 方法

您可以藉由下列方式終止進程:

  • 終止目前正在執行的進程。 例如,您可能需要終止在遠端電腦上執行的診斷程式。 如果無法從遠端控制應用程式,您可以直接終止該應用程式的程式。
  • 防止進程在第一個位置執行。 藉由在電腦上持續監視進程建立,您可以在啟動時立即識別並立即終止任何進程。 這提供一種方法,以確保某些應用程式 (例如透過網際網路下載大型媒體檔案的程式,) 永遠不會在特定電腦上執行。

注意

群組原則也可以用來限制在電腦上執行的程式。 不過,群組原則只能限制使用 [開始] 功能表 或 Windows Explorer 執行的程式;它不會影響使用其他方法啟動的程式,例如命令列。 相反地,不論進程如何啟動,WMI 都可以防止進程執行。

終止您不擁有的進程

若要終止您不擁有的進程,請啟用 SeDebugPrivilege 許可權。 在 VBScript 中,您可以使用下列幾行程式碼來啟用此許可權:

Set objLoc = createobject("wbemscripting.swbemlocator")
objLoc.Security_.privileges.addasstring "sedebugprivilege", true

如需在 C++ 中啟用此許可權的詳細資訊,請參閱 在 C++ 中啟用和停用許可權

範例

TechNet 資源庫 上多個伺服器上的終止執行進程 PowerShell 程式碼範例會終止在單一或多部電腦上執行的進程。

下列 VBScript 範例會終止應用程式Diagnose.exe目前正在執行的進程。

strComputer = "."
Set objWMIService = GetObject("winmgmts:" & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set colProcessList = objWMIService.ExecQuery("SELECT * FROM Win32_Process WHERE Name = 'Diagnose.exe'")
For Each objProcess in colProcessList
 objProcess.Terminate()
Next

下列 VBScript 範例會使用暫時事件取用者在啟動後立即終止進程。

strComputer = "."
Set objWMIService = GetObject("winmgmts:" & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set colMonitoredProcesses = objWMIService.ExecNotificationQuery("SELECT * FROM __InstanceCreationEvent " _
 & " WITHIN 1 WHERE TargetInstance ISA 'Win32_Process'")
i = 0
Do While i = 0
 Set objLatestProcess = colMonitoredProcesses.NextEvent
 If objLatestProcess.TargetInstance.Name = "Download.exe" Then
 objLatestProcess.TargetInstance.Terminate()
 End If
Loop

下列 VBScript 程式碼範例會連線到遠端電腦,並終止該電腦上的Notepad.exe。

strComputer = "FullComputerName" 
strDomain = "DOMAIN" 
strUser = InputBox("Enter user name") 
strPassword = InputBox("Enter password") 
Set objSWbemLocator = CreateObject("WbemScripting.SWbemLocator") 
Set objWMIService = objSWbemLocator.ConnectServer(strComputer, _ 
    "root\CIMV2", _ 
    strUser, _ 
    strPassword, _ 
    "MS_409", _ 
    "ntlmdomain:" + strDomain) 
Set colProcessList = objWMIService.ExecQuery("SELECT * FROM Win32_Process WHERE Name = 'notepad.exe'")
For Each objProcess in colProcessList
    objProcess.Terminate()
Next

下列 C++ 程式碼會終止本機電腦上的Notepad.exe進程。 在程式碼中) 指定 或 進程控制碼 (進程識別碼,以終止進程。 您可以在 Win32_Process 類別的 handle 屬性中找到這個值 (類別的索引鍵屬性) 。 藉由指定 Handle 屬性的值,您會提供您想要終止之類別實例的路徑。 如需連線到遠端電腦的詳細資訊,請參閱 範例:從遠端電腦取得 WMI 資料

#define _WIN32_DCOM

#include <iostream>
using namespace std;
#include <comdef.h>
#include <Wbemidl.h>

#pragma comment(lib, "wbemuuid.lib")

int main(int iArgCnt, char ** argv)
{
    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, 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 negotiates service
        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 local root\cimv2 namespace
    // and obtain pointer pSvc to make IWbemServices calls.
    hres = pLoc->ConnectServer(
        _bstr_t(L"ROOT\\CIMV2"), 
        NULL,
        NULL, 
        0, 
        NULL, 
        0, 
        0, 
        &pSvc
    );
     
    if (FAILED(hres))
    {
        cout << "Could not connect. Error code = 0x" 
             << hex << hres << endl;
        pLoc->Release();
        pSvc->Release();     
        CoUninitialize();
        return 1;                // Program has failed.
    }

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


    // Step 5: --------------------------------------------------
    // Set security levels for 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 ----

    // Set up to call the Win32_Process::Create method
    BSTR ClassName = SysAllocString(L"Win32_Process");

    /* YOU NEED TO CHANGE THE NUMBER VALUE OF THE HANDLE 
       (PROCESS ID) TO THE CORRECT VALUE OF THE PROCESS YOU 
       ARE TRYING TO TERMINATE (this provides a path to
       the class instance you are tying to terminate). */
    BSTR ClassNameInstance = SysAllocString(
        L"Win32_Process.Handle=\"3168\"");

    _bstr_t MethodName = (L"Terminate");
    BSTR ParameterName = SysAllocString(L"Reason");

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

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

    if (FAILED(hres))
    {
        cout << "Could not get the method. Error code = 0x" 
             << hex << hres << endl;
    }

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

    // Create the values for the in parameters
    VARIANT pcVal;
    VariantInit(&pcVal);
    V_VT(&pcVal) = VT_I4;

    // Store the value for the in parameters
    hres = pClassInstance->Put(L"Reason", 0,
        &pcVal, 0);

    // Execute Method
    hres = pSvc->ExecMethod(ClassNameInstance, MethodName, 0,
    NULL, pClassInstance, NULL, NULL);

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


    // Clean up
    //--------------------------
    VariantClear(&pcVal);
    SysFreeString(ClassName);
    SysFreeString(MethodName);
    pClass->Release();
    pInParamsDefinition->Release();
    pLoc->Release();
    pSvc->Release();
    CoUninitialize();
    return 0;
}

規格需求

需求
最低支援的用戶端
Windows Vista
最低支援的伺服器
Windows Server 2008
命名空間
Root\CIMV2
MOF
CIMWin32.mof
DLL
CIMWin32.dll

另請參閱

作業系統類別

Win32_Process

WMI 工作:效能監視

WMI 工作:進程