从php执行Powershell脚本
我试图从PHP执行powershell脚本,但它似乎不工作。从php执行Powershell脚本
脚本'newEvent.ps1'在Exchange服务器上创建一个事件。
$psPath = "powershell.exe";
$psDIR = "C:\\wamp\\www\\ant\\assets\\ps\\";
$psScript = "newEvent.ps1";
$runScript = $psDIR. $psScript;
$runCMD = $psPath." ".$runScript." 2>&1";
echo "\$psPath $psPath <br>";
echo "\$psDIR $psDIR <br>";
echo "\$psScript $psScript <br>";
echo "\$runScript $runScript <br>";
echo "\$runCMD $runCMD <br>";
exec($runCMD,$out,$ret);
echo "<pre>";
print_r($out);
print_r($ret);
echo "</pre>";
它输出:
$psPath powershell.exe
$psDIR C:\wamp\www\ant\assets\ps\
$psScript newEvent.ps1
$runScript C:\wamp\www\ant\assets\ps\newEvent.ps1
$runCMD powershell.exe C:\wamp\www\ant\assets\ps\newEvent.ps1 2>&1
Array
(
[0] => File C:\wamp\www\ant\assets\ps\newEvent.ps1 cannot be loaded because the execut
[1] => ion of scripts is disabled on this system. Please see "get-help about_signing"
[2] => for more details.
[3] => At line:1 char:39
[4] => + C:\wamp\www\ant\assets\ps\newEvent.ps1 <<<<
[5] => + CategoryInfo : NotSpecified: (:) [], PSSecurityException
[6] => + FullyQualifiedErrorId : RuntimeException
[7] =>
)
如果我运行命令行powershell.exe C:\wamp\www\ant\assets\ps\newEvent.ps1
,它工作正常。
这是我第一次尝试类似这样的事情。我跑了Set-ExecutionPolicy RemoteSigned -Scope LocalMachine
但它仍然给我同样的错误。 其实我跑Set-ExecutionPolicy unristricted
,但还是一样。
看起来你的命令被单引号包围。我想如果你删除它们,你的命令应该运行。
shell_exec
返回您运行命令的输出。要进一步诊断,请将输出存储在变量中,然后将其打印出来:
$output= shell_exec($runCMD);
echo('<pre>');
echo($output);
echo('</pre>');
确保启用了运行脚本。该功能默认关闭。您必须在要运行PowerShell脚本的每台计算机上启用脚本的执行。运行about help_signing
以获取更多信息。
Microsoft建议运行Set-ExecutionPolicy RemoteSigned -Scope LocalMachine
。这允许计算机上的所有用户帐户都可以毫无问题地运行本地脚本,但需要确认才能运行从互联网下载的脚本。这需要在管理提示符下运行。如果您运行的是64位操作系统,则需要从64位和32位的shell中执行此操作。
发现这个在其他网站上,我想我会通过它一起:
我调试使用的Windows API(创建具有重定向输入和输出一个孩子 过程)中的程序来捕获标准输出的 微软Windows PowerShell。
传递给PowerShell(-File开关)的脚本未执行,并且PowerShell刚挂起,直到被任务管理器终止。
事实证明,你需要使用无证参数“-InputFormat 无”:
C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe -InputFormat none -File file.ps1
这奏效了我。
这通常是链接到源(站点)的好形式,假设它是'!NSFW'。 – 2012-01-09 21:29:32
使用“-executionPolicy Unrestricted
”以及命令“powershell.exe
”。因此,命令将是:
powershell.exe -executionPolicy Unrestricted
然后它肯定会起作用。
看看你正在运行的命令行。 – 2011-03-15 20:17:11
确保进入32位和64位实例并设置执行策略,然后重试。 - > Set-ExecutionPolicy无限制 – 2012-06-04 13:18:41