DWORD InvokePSCommand(wchar_t* sessionId, wchar_t* command, _bstr_t& output) { HRESULT hr; bstr_t bstrStaticMethodName(L"Execute"); SAFEARRAY *psaStaticMethodArgs = NULL; variant_t vtSessionArg(sessionId == NULL ? L"Default" : sessionId); variant_t vtPSInvokeReturnVal; variant_t vtEmpty; variant_t vtCommandArg(command); LONG index = 0; psaStaticMethodArgs = SafeArrayCreateVector(VT_VARIANT, 0, 2); do { hr = SafeArrayPutElement(psaStaticMethodArgs, &index, &vtSessionArg); if (FAILED(hr)) { dprintf("[PSH] failed to prepare session argument: 0x%x", hr); break; } index++; hr = SafeArrayPutElement(psaStaticMethodArgs, &index, &vtCommandArg); if (FAILED(hr)) { dprintf("[PSH] failed to prepare command argument: 0x%x", hr); break; } // Invoke the method from the Type interface. hr = gClrPowershellType->InvokeMember_3( bstrStaticMethodName, static_cast<BindingFlags>(BindingFlags_InvokeMethod | BindingFlags_Static | BindingFlags_Public), NULL, vtEmpty, psaStaticMethodArgs, &vtPSInvokeReturnVal); if (FAILED(hr)) { dprintf("[PSH] failed to invoke powershell function 0x%x", hr); break; } output = vtPSInvokeReturnVal.bstrVal; } while (0); if (psaStaticMethodArgs != NULL) { SafeArrayDestroy(psaStaticMethodArgs); } if (SUCCEEDED(hr)) { return ERROR_SUCCESS; } return (DWORD)hr; }
void InvokeMethod(_TypePtr spType, wchar_t* method, wchar_t* command) { HRESULT hr; bstr_t bstrStaticMethodName(method); SAFEARRAY *psaStaticMethodArgs = NULL; variant_t vtStringArg(command); variant_t vtPSInvokeReturnVal; variant_t vtEmpty; psaStaticMethodArgs = SafeArrayCreateVector(VT_VARIANT, 0, 1); LONG index = 0; hr = SafeArrayPutElement(psaStaticMethodArgs, &index, &vtStringArg); if (FAILED(hr)) { wprintf(L"SafeArrayPutElement failed w/hr 0x%08lx\n", hr); return; } // Invoke the method from the Type interface. hr = spType->InvokeMember_3( bstrStaticMethodName, static_cast<BindingFlags>(BindingFlags_InvokeMethod | BindingFlags_Static | BindingFlags_Public), NULL, vtEmpty, psaStaticMethodArgs, &vtPSInvokeReturnVal); if (FAILED(hr)) { wprintf(L"Failed to invoke InvokePS w/hr 0x%08lx\n", hr); return; } else { // Print the output of the command wprintf(vtPSInvokeReturnVal.bstrVal); } SafeArrayDestroy(psaStaticMethodArgs); psaStaticMethodArgs = NULL; }