Reputation: 5524
I have the following code implemented:
$ServiceName = $_GET['Service'];
exec("echo . | powershell.exe -c get-service ".$ServiceName,$OutputArray);
echo "<pre>";
print_r($OutputArray);
echo "</pre>";
My $ServiceName
is assigned through get, but for this example.
$_GET['Service'] = "WinRM"; // Service Name is assigned to WinRM For *Windows Remote Management*
Now.. When I run this script, I get the following:
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] =>
)
Now, when I open Powershell, and run the following:
get-service WinRM
I get returned with the following output:
PS C:\Users\Administrator> get-service WinRM
Status Name DisplayName
------ ---- -----------
Running WinRM Windows Remote Management (WS-Manag...
This happens on a few other service names such as:
$Array = array(
"DNSServer" => "DNS",
"DHCP Client" => "DHCP",
"Web Server" => "IISADMIN",
"Windows Remote Management" => "WinRM"
);
This fails on DNS, IISADMIN, WinRM
in this example... But again, from PS I get returned with:
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...
My overall question is how to improve the reporting from Powershell to PHP and get accurate results from both ends?
This Does succeed some of the time depending on the service name. For example:
$ServiceName = "DHCP";
-- Which is why this Name is not included in the error debugging.. I get returned with:
Array
(
[0] =>
[1] => Status Name DisplayName
[2] => ------ ---- -----------
[3] => Running DHCP DHCP Client
[4] =>
[5] =>
)
Which is what I am looking for.
Upvotes: 1
Views: 528
Reputation: 317119
Instead of Powershell, consider querying the machine via COM and WMI:
$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
);
}
This will print
Service: Dhcp - Status: OK
The available properties for Win32_Service are listed here:
An alternative would be to exec
wmic:
exec('wmic Service where name="DHCP" get name, status /format:csv', $services);
Content of $services
would then be
Array
(
[0] =>
[1] => Node,Name,Status
[2] => MYCOMPUTER,Dhcp,OK
)
You can parse this easily with fgetcsv
. An alternate and easy to parse format would be rawxml
instead of csv
. See http://technet.microsoft.com/en-us/library/cc757287(v=ws.10).aspx for details
Upvotes: 1