6

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

2
  • C++ code will be fine for you as you tagged the question C and C++ ? Commented Apr 28, 2017 at 10:48
  • Hie. C would be more lucid to me! Commented Apr 28, 2017 at 10:51

3 Answers 3

11

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");
       }
}
Sign up to request clarification or add additional context in comments.

3 Comments

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.
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.
after running Set-ExecutionPolicy command the dialog asks to confirm ` Do you want to change the execution policy?`. How to deal with that?
3

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

Comments

1

In C++

#include <cstdlib>

std::system("command");

In c

#include <stdlib.h>

system("command");

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.