יום שבת, 19 באוקטובר 2013

How to call powershell script with C++ code

So you wrote powerShell script and you want to run the script.
You double click the script (extension .ps1) and what happened?
You see your script text, yeah, not what you thought, ah ?

So, in powershell, if you want to run your script, just press right click on the script and then "Run with PowerShell":















But maybe we are not the kind of guy that likes the right click. 
We are the "double click" guy.
So we can do it simply by writing C++ program:


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



Explanation:
·   We are using the access function to check if the path exist:
int _access(const char *path, int mode);
We define the mode with 0 to check if the path exist.
If the function returns 0, it means the given mode (in our case the mode that checks if the path exists) is correct.
For more information on Microsoft MSDN:
http://msdn.microsoft.com/en-us/library/1w06ktdy.aspx

·        Regarding c_str()
    Returns a pointer to an array that contains a null-terminated sequence of characters (i.e., a C-string) representing the current value of the string object.
      This array includes the same sequence of characters that make up the value of the string object plus an additional terminating null-character ('\0') at the end.

       So you could also write:

char arr[22] = {"d:\\callPowerShell.ps1"};
       ...
if(access(arr,0) == 0)
...
For more information:
http://www.cplusplus.com/reference/string/string/c_str/


Our powerShell script's code (callPowerShell.ps1) is:
get-process
read-host


So we will run the exe file and receive:














אין תגובות:

הוסף רשומת תגובה