1

我实现了以下代码:

$ServiceName = $_GET['Service'];
exec("echo . | powershell.exe -c get-service ".$ServiceName,$OutputArray);
        echo "<pre>";
            print_r($OutputArray);
        echo "</pre>";

My$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] => 
)

这就是我要找的。

4

1 回答 1

1

考虑通过COMWMI查询机器,而不是 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 的可用属性在此处列出:

execwmic的替代方法是:

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

于 2013-05-01T15:20:58.623 回答