-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapi.php
More file actions
47 lines (39 loc) · 1.79 KB
/
api.php
File metadata and controls
47 lines (39 loc) · 1.79 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
<?php
// api.php
// 作为前端和PowerShell脚本之间的接口
// 调试完成后,移除或注释掉错误报告
// error_reporting(E_ALL);
// ini_set('display_errors', 1);
header('Content-Type: application/json'); // 设置响应头为JSON格式
// 使用 __DIR__ 来动态获取当前脚本所在的目录
$psScriptPath = __DIR__ . '\\get_server_info.ps1';
// 检查 PowerShell 脚本是否存在
if (!file_exists($psScriptPath)) {
echo json_encode(['error' => 'PowerShell 脚本未找到。请检查 $psScriptPath 配置。', 'path' => $psScriptPath]);
exit;
}
// 构建执行 PowerShell 脚本的命令
// 重点:在PowerShell命令块内部,显式设置 [Console]::OutputEncoding 为 UTF8。
// 这会强制PowerShell进程的标准输出使用UTF-8编码。
$command = "powershell.exe -ExecutionPolicy Bypass -NoProfile -NonInteractive -Command \"[Console]::OutputEncoding = [System.Text.Encoding]::UTF8; & \\\"{$psScriptPath}\\\"\"";
// 执行 PowerShell 脚本并捕获输出
$output = shell_exec($command);
// 检查 shell_exec 是否成功执行
if ($output === null) {
echo json_encode(['error' => '无法执行 PowerShell 命令。请检查权限或 PowerShell 安装。']);
} else {
// 尝试解码 JSON 输出
$data = json_decode($output, true);
if (json_last_error() !== JSON_ERROR_NONE) {
// 如果 JSON 解码失败,可能是 PowerShell 脚本有错误输出或格式不正确
echo json_encode([
'error' => 'PowerShell 脚本返回了无效的 JSON 数据。',
'raw_output' => $output, // 返回原始输出以便调试
'json_error_message' => json_last_error_msg()
]);
} else {
// 成功解码,返回数据
echo json_encode($data);
}
}
?>