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 檔案總管執行的程式;它不會影響開始使用其他方法的程式,例如命令行。 相反地,無論進程是如何啟動的,WMI 都可以防止進程執行。

終止您不擁有的進程

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

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

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

範例

下列 VBScript 範例會終止應用程式 Diagnostic.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 程式代碼範例會連線到遠端計算機,並終止該電腦上的 記事本.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++ 程式代碼會終止本機電腦上的 記事本.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
Namespace
Root\CIMV2
MOF
CIMWin32.mof
DLL
CIMWin32.dll

另請參閱

作業系統類別

Win32_Process

WMI 工作:效能監視器

WMI 工作:進程