Public Sub PS_Add_Printer()
Dim PSscript As String
Dim PSscriptFile As String
Dim WShell As Object 'WshShell
Dim WSExec As Object 'WshExec
Dim portName As String
Dim printerName As String
Dim driverName As String
Dim PScommand As String
Dim PSerror As Variant, PSoutput As Variant, i As Long
portName = "C:\Temp\PrintToPDF.pdf"
printerName = "Print To PDF"
driverName = "Microsoft Print To PDF"
PSscript = "[cmdletbinding()]" & vbCrLf & _
"param([Parameter(Mandatory)] [string]$PrinterName, [Parameter(Mandatory)] [string]$PortName, [Parameter(Mandatory)] [string]$DriverName)" & vbCrLf & _
" Write-Host ""-PrinterName '$PrinterName' -PortName '$PortName' -DriverName '$DriverName'""" & vbCrLf & _
" try {" & vbCrLf & _
" Write-Host ""Get printer port '$PortName'""" & vbCrLf & _
" $null = Get-PrinterPort -Name $PortName" & vbCrLf & _
" }" & vbCrLf & _
" catch {" & vbCrLf & _
" Write-Host ""Port does not exist: add printer port '$PortName'""" & vbCrLf & _
" Add-PrinterPort -Name $PortName" & vbCrLf & _
" }" & vbCrLf & _
" try {" & vbCrLf & _
" Write-Host ""Add printer '$PrinterName' with driver '$DriverName'""" & vbCrLf & _
" $null = Get-PrinterDriver -Name $DriverName" & vbCrLf & _
" Add-Printer -Name $PrinterName -PortName $PortName -DriverName $DriverName" & vbCrLf & _
" Write-Host ""Printer added successfully""" & vbCrLf & _
" }" & vbCrLf & _
" catch {" & vbCrLf & _
" Write-Host ""Failed to add printer, error was:""" & vbCrLf & _
" $PSCmdlet.WriteError($_)" & vbCrLf & _
" }"
PSscriptFile = Environ("TEMP") & "\Add_Printer.ps1"
Open PSscriptFile For Output As #1
Print #1, PSscript
Close #1
PScommand = "powershell -ExecutionPolicy Bypass -File " & Q(PSscriptFile) & " -PrinterName " & Q(printerName) & " -PortName " & Q(portName) & " -DriverName " & Q(driverName) & " -ErrorAction Stop"
Set WShell = CreateObject("WScript.Shell")
Set WSExec = WShell.Exec(PScommand)
PSoutput = Split(WSExec.StdOut.ReadAll, vbCrLf)
Debug.Print "StdOut:"
For i = 0 To UBound(PSoutput)
Debug.Print PSoutput(i)
Next
PSerror = Split(WSExec.StdErr.ReadAll, vbCrLf)
Debug.Print "StdErr:"
For i = 0 To UBound(PSerror)
Debug.Print PSerror(i)
Next
Kill PSscriptFile
End Sub
Private Function Q(text As String) As String
Q = Chr(34) & text & Chr(34)
End Function