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++
3 Answers
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");
}
}
3 Comments
Vesper
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
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.Viktor
after running Set-ExecutionPolicy command the dialog asks to confirm ` Do you want to change the execution policy?`. How to deal with that?
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");