我实现了以下代码:
$ServiceName = $_GET['Service'];
exec("echo . | powershell.exe -c get-service ".$ServiceName,$OutputArray);
echo "<pre>";
print_r($OutputArray);
echo "</pre>";
我的$ServiceName
是通过get分配的,但是对于此示例。
$_GET['Service'] = "WinRM"; // Service Name is assigned to WinRM For *Windows Remote Management*
现在..当我运行这个脚本时,我得到以下内容:
Array
(
[0] => Get-Service : Cannot find any service with service name 'WinRM'.
[1] => At line:1 char:12
[2] => + get-service <<<< WinRM
[3] => + CategoryInfo : ObjectNotFound: (WinRM:String) [Get-Service], Se
[4] => rviceCommandException
[5] => + FullyQualifiedErrorId : NoServiceFoundForGivenName,Microsoft.PowerShell.
[6] => Commands.GetServiceCommand
[7] =>
)
现在,当我打开Powershell时,运行以下命令:
get-service WinRM
我收到以下输出:
PS C:\Users\Administrator> get-service WinRM
Status Name DisplayName
------ ---- -----------
Running WinRM Windows Remote Management (WS-Manag...
这种情况发生在一些其他服务名称上,例如:
$Array = array(
"DNSServer" => "DNS",
"DHCP Client" => "DHCP",
"Web Server" => "IISADMIN",
"Windows Remote Management" => "WinRM"
);
这个示例中的DNS, IISADMIN, WinRM
失败了......但是再一次,从PS我得回来了:
PS C:\Users\Administrator> get-service DNS,IISADMIN,WinRM
Status Name DisplayName
------ ---- -----------
Running DNS DNS Server
Running IISADMIN IIS Admin Service
Running WinRM Windows Remote Management (WS-Manag...
我的整体问题是如何改进从Powershell到PHP的报告并从两端获得准确的结果?
根据服务名称,这有时会成功。例如:
$ServiceName = "DHCP";
- 这就是错误调试中没有包含此名称的原因..我的回复是:
Array
(
[0] =>
[1] => Status Name DisplayName
[2] => ------ ---- -----------
[3] => Running DHCP DHCP Client
[4] =>
[5] =>
)
这就是我要找的。 p>
答案 0 :(得分:1)
考虑通过COM和WMI查询机器,而不是Powershell:
$wmi = new COM('WinMgmts:{impersonationLevel=impersonate}!root/cimv2');
$result = $wmi->ExecQuery('Select * from Win32_Service where Name="Dhcp"');
foreach ($result as $share) {
printf(
'Service: %s - Status: %s %s',
$share->Name,
$share->Status,
PHP_EOL
);
}
这将打印
Service: Dhcp - Status: OK
此处列出了Win32_Service的可用属性:
替代方案是exec
wmic:
exec('wmic Service where name="DHCP" get name, status /format:csv', $services);
$services
的内容将是
Array
(
[0] =>
[1] => Node,Name,Status
[2] => MYCOMPUTER,Dhcp,OK
)
您可以使用fgetcsv
轻松解析此问题。另一种易于解析的格式是rawxml
,而不是csv
。有关详细信息,请参阅http://technet.microsoft.com/en-us/library/cc757287(v=ws.10).aspx