5

In my case, I needed to call a powershell script from a c or c++ code source, found few links which were pretty clumsy and not good with c++, I simply want a roadmap if its possible invoking a powershell script which lists directory contents from a code snippet written in c or c++

rhym1n
  • 87
  • 1
  • 2
  • 9

3 Answers3

10

C++ code :

#include<iostream>
#include <io.h>   // For access().
#include <sys/types.h>  // For stat().
#include <sys/stat.h>   // For stat().
#include <string>
using namespace std;


void main()
{
       string strPath = "d:\\callPowerShell.ps1";
//access function:
       //The function returns 0 if the file has the given mode.
       //The function returns –1 if the named file does not exist or does not have the given mode
       if(access(strPath.c_str(),0) == 0)
       {

              system("start powershell.exe Set-ExecutionPolicy RemoteSigned \n");
              system("start powershell.exe d:\\callPowerShell.ps1");
              system("cls");
       }
       else
       {
              system("cls");
              cout << "File is not exist";
              system("pause");
       }
}
W.draoui
  • 383
  • 2
  • 3
  • 15
  • It'll be better if you'd supply `-ExecutionPolicy` parameter right in the same command with the script. Also `strPath` is assigned but not used. – Vesper Apr 28 '17 at 11:02
  • 3
    For future reference, this answer can be greatly improved with vc++17 supporting c++17 and therefore the filesystem TS allowing `std::filesystem::exists(...);` rather than system specific includes and functions. Also use of `std::system` rather than just C's `system` is recommended, `using namespace std;` could cause redefinition issues for the `system` function. – pointerless Oct 22 '18 at 10:26
  • after running Set-ExecutionPolicy command the dialog asks to confirm ` Do you want to change the execution policy?`. How to deal with that? – Viktor Oct 23 '22 at 11:21
2

First error :

#include <io.h>   // For access().

access is in this lib:

#include <cstdlib>

Next :

error: 'system' was not declared in this scope

#include <unistd.h>

And finally :

The caractere '\' is a special caractere for C/C++ then you have to add another '\' like :

system("start powershell.exe C:\\users\\sqtk-mal\\script1.ps1");
Rapido
  • 301
  • 4
  • 12
1

In C++

#include <cstdlib>

std::system("command");

In c

#include <stdlib.h>

system("command");
Rapido
  • 301
  • 4
  • 12