Change Default Printer paper size with PHP powershell script

0

I am trying to change Default printer paper size from PHP

Index.php

<?php
$printer = Shell_Exec ('powershell.exe -executionpolicy bypass -NoProfile -Command "(Get-WmiObject win32_printer | Where-Object Default -eq $True).Name"');

$printer = substr($printer, 0, -1);
$printer = '"' . $printer . '"';
$cmd = ('powershell.exe -executionpolicy bypass -NoProfile -Command ../A5.ps1 ' .$printer);
echo shell_exec($cmd);
?>

A5.ps1

$printer=$args[0]
Set-PrintConfiguration -PrinterName $printer -PaperSize A5

Error

Set-PrintConfiguration : The specified printer was not found. At C:\Users\t4taa\Desktop\phpdesktop\A5.ps1:2 char:1 + Set-PrintConfiguration -PrinterName $printer -PaperSize A5 + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : NotSpecified: (MSFT_PrinterConfiguration:ROOT/StandardCi...erConfiguration) [Set-PrintCo nfiguration], CimException + FullyQualifiedErrorId : HRESULT 0x80070709,Set-PrintConfiguration

When I run script file from PowerShell works fine but from PHP it's refuse to take printer name or miss double quotes, how to resolve this problem.

php
powershell
printing
asked on Stack Overflow Aug 3, 2020 by Sheeraz Ahmad • edited Aug 3, 2020 by Sheeraz Ahmad

1 Answer

1

Why not change the A5.ps1 into

$printer = (Get-WmiObject win32_Printer | Where-Object { $_.Default -eq $true }).Name
Set-PrintConfiguration -PrinterName $printer -PaperSize A5

to have powershell figure out the default printer name AND set the papersize.

That way you can do in the index.php:

<?php
$cmd = ('powershell.exe -ExecutionPolicy Bypass -NoProfile -File ../A5.ps1');
echo shell_exec($cmd);
?>

Use -File instead of -Command

answered on Stack Overflow Aug 3, 2020 by Theo

User contributions licensed under CC BY-SA 3.0