2

I was wondering how to write code in c++ that could send commands to powershell. I'd like to be able to parse the output as well but at this point I'd just like to begin learning how to run commands and can learn to parse the output later. Thank you ahead of time to anyone able to help.

sdd1208
  • 125
  • 1
  • 2
  • 5
  • Check out these other threads. They are c# based, but the concept is the same. http://stackoverflow.com/questions/13251076/calling-powershell-from-c-sharp http://stackoverflow.com/questions/17067971/invoking-powershell-cmdlets-from-c-sharp – Jim Oct 28 '13 at 12:45
  • Here is another forum post with helpful links: http://forums.iis.net/t/1200231.aspx – Jim Oct 28 '13 at 12:52
  • Are you willing to write C++/CLI code because that is what you're going to need to do. The PowerShell engine has a .NET API. – Keith Hill Oct 28 '13 at 14:16

1 Answers1

1

Here's a small sample that should get you going:

#include "stdafx.h"

using namespace System;
using namespace System::Collections::ObjectModel;
using namespace System::Management::Automation;

int _tmain(int argc, _TCHAR* argv[])
{
    PowerShell^ _ps = PowerShell::Create();
    _ps->AddScript("Get-ChildItem C:\\");
    auto results = _ps->Invoke();
    for (int i = 0; i < results->Count; i++)
    {
        String^ objectStr = results[i]->ToString();
        Console::WriteLine(objectStr);
    }

    return 0;
}

Make sure the /clr switch is enabled for your C++ project.

Keith Hill
  • 194,368
  • 42
  • 353
  • 369