Conner X
Conner X

Reputation: 115

How to print a test page to a specified printer?

I'm writing a small ps1 script to clear the queue and restart the spool on a printer of the end user's choosing. What I have so far does as intended with the Default Printer on a given machine, but I need the end user to be able to select exactly which printer is giving them problems. Here is the current functional script:

net stop spooler

Remove-Item C:\Windows\System32\spool\PRINTERS\* -Force

net start spooler

$printer = Get-WmiObject -Query " SELECT * FROM Win32_Printer WHERE Default=$true"

$PrintTestPage = $printer.PrintTestPage()  

$wshell = New-Object -ComObject Wscript.Shell

$wshell.Popup("I found a problem that I was able to fix.  Please try to print again.",0,"Printer Helper",0x1)

I've tried altering the script in the following manner to allow user input.

    net stop spooler

Remove-Item C:\Windows\System32\spool\PRINTERS\* -Force

net start spooler

get-printer

$printer = Read-Host -Prompt 'Please Type In The Name Of The Printer That You Are Having Problems With'

$PrintTestPage = $printer.PrintTestPage()  

$wshell = New-Object -ComObject Wscript.Shell

$wshell.Popup("I found a problem that I was able to fix.  Please try to print again.",0,"Printer Helper",0x1)

However, I get the following error.

Method invocation failed because [System.String] does not contain a method named 'PrintTestPage'.

How can I work around this?

Upvotes: 0

Views: 3152

Answers (1)

Mathias R. Jessen
Mathias R. Jessen

Reputation: 174485

Read-Host returns a string - not an instance of the Win32_Printer wmi class.

You can use the input from Read-Host to retrieve the instance:

$PrinterName = Read-Host 'Please Type In The Name Of The Printer That You Are Having Problems With'

$PrinterInstance = [wmi]"\\.\root\cimv2:Win32_Printer.DeviceID='$PrinterName'"

# Now you can call PrintTestPage()
$PrinterInstance.PrintTestPage()

Upvotes: 3

Related Questions