使用C++调用带有库的powershell脚本

Call powershell script with libraries using C++

本文关键字:powershell 脚本 C++ 调用 使用      更新时间:2023-10-16

我有一个名为"email.ps1"的powershell脚本,代码如下:

$env:PSModulePath = $env:PSModulePath + ";C:TMPcodigospowershelllibraries"
. library.ps1
. inithialize.ps1
(...)

我试着用C++程序用系统命令调用它。不幸的是,该程序找不到库"library"answers"inithialize",但当我在没有C++程序的情况下使用powershell/cmd调用脚本时,它确实可以工作。

我已经试过这些电话,但没有成功

system("full_path_to_script/email.ps1")
system("powershell full_path_to_script/email.ps1")
system("powershell.exe full_path_to_script/email.ps1")

有什么想法吗?

您正在点源library.ps1inithialize.ps1脚本,而不是使用Import-Module将它们作为模块导入。因此,修改PSModulePath变量将没有任何效果,因为它只由导入模块使用。

当点源时,你需要包括完整的路径,比如:

. C:TMPcodigospowershelllibrarieslibrary.ps1
. C:TMPcodigospowershelllibrariesinithialize.ps1

或者,您可以将这些库转换为真正的PowerShell模块。看看msdn上的帮助。