以编程方式获取powershell.exe的完整路径

To get full path of powershell.exe programmatically

本文关键字:路径 exe powershell 编程 方式 获取      更新时间:2023-10-16

我需要获得Powershell.exe的完整路径(绝对路径)才能在代码中运行Powershell脚本。有人能向我推荐任何库或内置方法来做到这一点吗。

我在windows.h中尝试了boost文件系统的absolute()方法和getFUllPathName()方法。但我所能得到的只是我项目的当前工作目录。

或者(如果您不喜欢依赖环境变量),您也可以查询注册表。Powershell在安装时会写入一个FriendlyTypeName值,在我的机器上它是

@"%systemroot%\system32\windowspowershell \v1.0\powershell.exe",-107

其包含路径。

注册表项为HKEY_CLASSES_ROOTMicrosoft.PowerShellConsole.1FriendlyTypeName

使用Windows API查询注册表。

解决方案1:Powershell.exe很可能在您的路径中,所以您可以在C++代码中使用它。

system("powershell.exe -Command .\script.bat");

只需将.\script.bat替换为脚本的路径即可。

解决方案2:您可以使用环境变量来获取程序中powershell的路径。只需在系统中设置一个名为PSPATH的环境变量,或者其他什么,使用powershell目录(C:WINDOWSsystem32WindowsPowerShellv1.0)的路径。然后您可以使用getenv()函数来获取它。

示例:

char* psVar = getenv("PSPATH");
if (psVar != NULL)
{
    std::string psPath = psVar;
    std::string psScript = ".\script.bat";
    system(psPath + "\powershell.exe -Command " + psScript);
}