How to call a powershell script from a C code
Asked Answered
L

3

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

Lamphere answered 28/4, 2017 at 10:43 Comment(2)
C++ code will be fine for you as you tagged the question C and C++ ?Samekh
Hie. C would be more lucid to me!Lamphere
S
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");
       }
}
Samekh answered 28/4, 2017 at 10:49 Comment(3)
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.Unless
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.Microsporophyll
after running Set-ExecutionPolicy command the dialog asks to confirm ` Do you want to change the execution policy?`. How to deal with that?Continuation
U
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");
Understudy answered 3/5, 2017 at 20:54 Comment(0)
U
1

In C++

#include <cstdlib>

std::system("command");

In c

#include <stdlib.h>

system("command");
Understudy answered 28/4, 2017 at 10:49 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.