Created
December 30, 2017 20:43
-
-
Save parzibyte/e3b904d69cad1867929941fdddf3afbd to your computer and use it in GitHub Desktop.
Listar sólo las impresoras compartidas usando PHP y powershell de Windows
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
$ruta_powershell = 'c:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe'; #Necesitamos el powershell | |
$opciones_para_ejecutar_comando = "-c";#Ejecutamos el powershell y necesitamos el "-c" para decirle que ejecutaremos un comando | |
$espacio = " "; #ayudante para concatenar | |
$comillas = '"'; #ayudante para concatenar | |
$comando = 'get-WmiObject -class Win32_printer |ft shared, name'; #Comando de powershell para obtener lista de impresoras | |
$delimitador = "True"; #Queremos solamente aquellas en donde la línea comienza con "True" | |
$lista_de_impresoras = array(); #Aquí pondremos las impresoras | |
exec( | |
$ruta_powershell | |
. $espacio | |
. $opciones_para_ejecutar_comando | |
. $espacio | |
. $comillas | |
. $comando | |
. $comillas, | |
$resultado, | |
$codigo_salida); | |
if ($codigo_salida === 0) { | |
if (is_array($resultado)) { | |
#Omitir los primeros 3 datos del arreglo, pues son el encabezado | |
for($x = 3; $x < count($resultado); $x++){ | |
$impresora = trim($resultado[$x]); | |
# Ignorar los espacios en blanco o líneas vacías | |
if (strlen($impresora) > 0) { | |
# Comprobar si comienzan con "True", para ello usamos el delimitador declarado arriba | |
if (strpos($impresora, $delimitador) === 0){ | |
#Limpiar el nombre | |
$nombre_limpio = substr($impresora, strlen($delimitador) + 1, strlen($impresora) - strlen($delimitador) + 1); | |
#Finalmente agregarla al array | |
array_push($lista_de_impresoras, $nombre_limpio); | |
} | |
} | |
} | |
} | |
echo "<pre>"; | |
print_r($lista_de_impresoras); | |
echo "</pre>"; | |
} else { | |
echo "Error al ejecutar el comando."; | |
} | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment