如何从 C 代码调用 powershell 脚本

rhy*_*m1n 3 c c++ directory powershell directory-listing

就我而言,我需要从 ac 或 c++ 代码源调用 powershell 脚本,发现很少有非常笨拙且不适合 c++ 的链接,如果可能的话,我只想要一个路线图,它可以调用从代码中列出目录内容的 powershell 脚本用 c 或 c++ 编写的代码段

W.d*_*oui 6

C++ 代码:

#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");
       }
}
Run Code Online (Sandbox Code Playgroud)

  • 为了将来参考,这个答案可以通过支持 c++17 的 vc++17 大大改进,因此文件系统 TS 允许 `std::filesystem::exists(...);` 而不是系统特定的包含和函数。还建议使用 `std::system` 而不仅仅是 C 的 `system`,`using namespace std;` 可能会导致 `system` 函数的重新定义问题。 (2认同)

Rap*_*ido 1

在 C++ 中

#include <cstdlib>

std::system("command");
Run Code Online (Sandbox Code Playgroud)

在c

#include <stdlib.h>

system("command");
Run Code Online (Sandbox Code Playgroud)