PHP使用shell_exec调用PowerShell 7.4无输出问题求助
问题描述
我有一个用于输出系统变量值的PowerShell脚本env_output.ps1,代码如下:
$Env:UserDomain $Env:ComputerName $Env:UserName
使用PHP的shell_exec函数调用powershell.exe(PowerShell v5)时可正常获取输出:
$output_switch = shell_exec('powershell.exe -File C:\inetpub\env_output.ps1'); print_r ($output_switch);
但切换为调用pwsh.exe(PowerShell 7.4)时却没有输出:
$output_switch = shell_exec('pwsh.exe -File C:\inetpub\env_output.ps1'); print_r ($output_switch);
运行环境为Windows Server 2019,搭配IIS和PHP,两个PowerShell可执行文件均已加入系统路径。
解决方案
1. 排查执行策略与权限问题
PowerShell 7的执行策略默认可能更严格,且IIS运行PHP的用户(通常是IIS应用池标识或IIS_IUSRS组)可能缺少执行权限:
- 以管理员身份打开PowerShell 7,执行命令查看当前执行策略:
Get-ExecutionPolicy -List - 若需要,调整执行策略为
RemoteSigned(兼顾安全与脚本执行需求):Set-ExecutionPolicy RemoteSigned -Scope LocalMachine - 给
env_output.ps1所在目录、pwsh.exe安装目录添加IIS应用池用户的读取/执行权限。
2. 修正输出编码兼容问题
PowerShell 7默认输出编码为UTF-16,而PHP的shell_exec可能无法正确解析。可以通过两种方式处理:
- 调用时强制指定输出编码:
$output_switch = shell_exec('pwsh.exe -Command "$Env:UserDomain; $Env:ComputerName; $Env:UserName" | Out-String -Encoding UTF8'); print_r($output_switch); - 修改脚本,明确编码输出:
[Console]::OutputEncoding = [System.Text.Encoding]::UTF8 $Env:UserDomain $Env:ComputerName $Env:UserName
3. 显式指定pwsh.exe完整路径
尽管已加入系统路径,但IIS应用池的环境变量可能未加载系统路径,直接使用完整路径调用:
$output_switch = shell_exec('C:\Program Files\PowerShell\7\pwsh.exe -File C:\inetpub\env_output.ps1'); print_r($output_switch);
注意:路径需根据PowerShell 7实际安装位置调整
4. 捕获错误输出排查问题
shell_exec仅捕获标准输出,将错误输出重定向到标准输出,可查看具体执行报错:
$output_switch = shell_exec('pwsh.exe -File C:\inetpub\env_output.ps1 2>&1'); print_r($output_switch);
内容的提问来源于stack exchange,提问作者Singsiblaw
相关产品推荐
相关产品推荐

