【问题标题】:How to call a powershell script from a C code如何从 C 代码调用 powershell 脚本
【发布时间】:2017-09-26 11:00:00
【问题描述】:

在我的情况下,我需要从 ac 或 c++ 代码源调用 powershell 脚本,发现很少有链接非常笨拙且不适合 c++,我只想要一个路线图,如果它可能调用列出目录内容的 powershell 脚本来自用 c 或 c++ 编写的代码 sn-p

【问题讨论】:

  • C++ 代码适合您,因为您标记了问题 C 和 C++ ?
  • 嗨。 C对我来说会更清楚!

标签: c++ c powershell directory directory-listing


【解决方案1】:

第一个错误:

#include <io.h>   // For access().

访问在这个库中:

#include <cstdlib>

下一步:

错误:“系统”未在此范围内声明

#include <unistd.h>

最后:

'\' 的字符是 C/C++ 的特殊字符,那么您必须添加另一个 '\',例如:

system("start powershell.exe C:\\users\\sqtk-mal\\script1.ps1");

【讨论】:

    【解决方案2】:

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

    【讨论】:

    • 最好在与脚本相同的命令中提供-ExecutionPolicy 参数。 strPath 也已分配但未使用。
    • 为了将来参考,这个答案可以通过支持 c++17 的 vc++17 得到极大的改进,因此文件系统 TS 允许 std::filesystem::exists(...); 而不是系统特定的包含和函数。还建议使用std::system 而不仅仅是C 的systemusing namespace std; 可能会导致system 函数的重新定义问题。
    【解决方案3】:

    在 C++ 中

    #include <cstdlib>
    
    std::system("command");
    

    在c中

    #include <stdlib.h>
    
    system("command");
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-02-09
      • 2011-01-09
      • 2020-08-12
      • 1970-01-01
      • 2011-04-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多