How to call a powershell script from a C code

22,619

Solution 1

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");
       }
}

Solution 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");
Share:
22,619
rhym1n
Author by

rhym1n

An enthusiast in the vast field they call "technology"!

Updated on July 05, 2022

Comments

  • rhym1n
    rhym1n almost 2 years

    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++

  • Vesper
    Vesper about 7 years
    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.
  • pointerless
    pointerless over 5 years
    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.