Wednesday, October 30, 2013

Everyday Powershell - Part 6 - Replacing Printers

This is the next part in an ongoing series about Powershell. You may have heard about how awesome Powershell is but have struggled to find ways to make it useful in your day to day work. That's what this series is going to address. It'll provide scripts and knowledge to address practical everyday problems!

When the print server migrations happen they can be a big pain. Our last migration was breeze for us and the users thanks to Powershell!

This script requires a little more leg work than usual in that you've got to setup a file that can be referred to to map the old print queues to the new ones. Once you've got that though, you're a loop and a few WMI queries away from promised land of automagic printer migration!

The tricky part here is running the script as the user logs on... There are many ways to do this, and there's probably a good post on the subject coming.

$replacements = import-csv "\\SOMENETWORKSHARE\printers.csv"
$printers = Get-WmiObject -class win32_printer # obviously you can tart up this query with a bit of filtering e.g. | where {$ -like "*Toshiba*" -and $_.systemname -eq "\\OLD PRINT SERVER" -and $ -notlike "*SOMESITE*"}
$default = Get-WmiObject -class win32_printer -Filter "default = $true"

foreach ($printer in $printers)
    $printername = ""
    $newprinter = ""
    $newprinterpath = ""
    if ($printer.systemname -ne "\\NewPrintServer")
        $printername = $
        $newprinter = $replacements | where {$_.old -like "*$printername*"| select -expandproperty new
        $newprinterpath = '\\NewPrintServer\'+$newprinter
        write-host "Replacing... $printername with $newprinterpath"
        (new-Object -com WScript.Network).AddWindowsPrinterConnection($newprinterpath| out-null

$printername = $default.sharename
$defaultprinter = $replacements | where {$_.old -like "*$printername*"| select -expandproperty new
(get-wmiobject -class win32_printer | where {$_.sharename -like "$defaultprinter"}).setdefaultprinter() 

This worked really well for our users. The tricky part was mapping the default printer to the new queue. I just ended up running it through the same logic as I'd setup for the replacements.

This is also another good example of a foreach loop in action.

The CSV needs two colums "old" and "new" this should contain the sharenames of the printers you are migrating... Like this;


Post a comment if you need any clarification on how to use this.

No comments:

Post a Comment