{"id":53713,"date":"2009-05-20T20:24:00","date_gmt":"2009-05-20T20:24:00","guid":{"rendered":"https:\/\/blogs.technet.microsoft.com\/heyscriptingguy\/2009\/05\/20\/hey-scripting-guy-how-can-i-use-windows-powershell-to-remove-old-printer-connections-list-printers-and-set-new-default-printers\/"},"modified":"2009-05-20T20:24:00","modified_gmt":"2009-05-20T20:24:00","slug":"hey-scripting-guy-how-can-i-use-windows-powershell-to-remove-old-printer-connections-list-printers-and-set-new-default-printers","status":"publish","type":"post","link":"https:\/\/devblogs.microsoft.com\/scripting\/hey-scripting-guy-how-can-i-use-windows-powershell-to-remove-old-printer-connections-list-printers-and-set-new-default-printers\/","title":{"rendered":"Hey, Scripting Guy! How Can I Use Windows PowerShell to Remove Old Printer Connections, List Printers, and Set New Default Printers?"},"content":{"rendered":"<h2><img decoding=\"async\" class=\"nearGraphic\" title=\"Hey, Scripting Guy! Question\" border=\"0\" alt=\"Hey, Scripting Guy! Question\" align=\"left\" src=\"https:\/\/devblogs.microsoft.com\/wp-content\/uploads\/sites\/29\/2019\/02\/q-for-powertip.jpg\" width=\"34\" height=\"34\"> Hey, Scripting Guy! Well it finally happened. Our budget request for new printers was approved. We have gotten them unboxed, distributed, and hooked up to the LAN. We have even downloaded the latest drivers from the Internet, and updated the firmware on several of the printers. The drivers are installed on the print servers, and the shares have been created. Now I have to remove the old printer connections from the client workstations, and set new default printers. Can I do this in Windows PowerShell?<\/p>\n<p>&#8211; BP<\/p>\n<p><img decoding=\"async\" border=\"0\" alt=\"Spacer\" src=\"https:\/\/devblogs.microsoft.com\/scripting\/wp-content\/uploads\/sites\/29\/2019\/05\/spacer.gif\" width=\"5\" height=\"5\"><img decoding=\"async\" class=\"nearGraphic\" title=\"Hey, Scripting Guy! Answer\" border=\"0\" alt=\"Hey, Scripting Guy! Answer\" align=\"left\" src=\"https:\/\/devblogs.microsoft.com\/wp-content\/uploads\/sites\/29\/2019\/02\/a-for-powertip.jpg\" width=\"34\" height=\"34\"><\/p>\n<p>Hi BP,<\/p>\n<p>We are absolutely swamped with the 2009 Summer Scripting Games, which are coming up I the week of June 15. We are busy rounding up guest commentators&mdash;this year we will have 40 of them! Trying to select 40 commentators from around the scripting world is a bit of a challenge, but we have rounded up a group of some of the best scripters in the world. About half of the commentators have already turned in their entries (the Games are so much fun, they could not wait to get started) and Ed was impressed&mdash;and in several cases actually astonished&mdash;by the creative approaches to some events. We absolutely guarantee that you will similarly be blown away by some of the scripts written by the guest commentators. One commentator even went so far as to&hellip;sorry, can&rsquo;t reveal this yet. Cliffhanger! Okay, about your printer problem.<\/p>\n<table id=\"EXC\" class=\"dataTable\" cellspacing=\"0\" cellpadding=\"0\">\n<thead><\/thead>\n<tbody>\n<tr class=\"record\" valign=\"top\">\n<td>\n<p class=\"lastInCell\">This week we will examine printing. There are lots of resources related to printing on the TechNet Script Center. There is a collection of <a href=\"http:\/\/www.microsoft.com\/technet\/scriptcenter\/resources\/qanda\/printing.mspx\" target=\"_blank\">Hey, Scripting Guy! articles<\/a> that lists 24 articles relates to both server-side and client-side printing. We have almost 50 scripts in the <a href=\"http:\/\/www.microsoft.com\/technet\/scriptcenter\/scripts\/printing\/default.mspx\" target=\"_blank\">printer section<\/a> of the <a href=\"http:\/\/www.microsoft.com\/technet\/scriptcenter\/scripts\/default.mspx\" target=\"_blank\">Script Center Script Repository<\/a>. There are also almost 50 scripts in the <a href=\"http:\/\/www.microsoft.com\/technet\/scriptcenter\/csc\/scripts\/print\/default.mspx\" target=\"_blank\">printer section<\/a> of the Community-Submitted Scripts Center. We have some good technical information about printing in the <a href=\"http:\/\/www.microsoft.com\/technet\/scriptcenter\/guide\/sas_prn_overview.mspx\" target=\"_blank\">Scripting Guide<\/a>. All those resources are in VBScript. To use them in Windows PowerShell, you would have to translate the scripts into PowerShell. The Microsoft Press book, <a href=\"http:\/\/www.microsoft.com\/MSPress\/books\/authors\/auth9541.aspx\" target=\"_blank\">Windows PowerShell Scripting Guide<\/a>, has a whole chapter devoted to printing.<\/p>\n<\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<div class=\"dataTableBottomMargin\"><\/div>\n<p class=\"MsoNormal\">The SetDefaultPrinterDeletePrinterConnection.ps1 script is seen here. It uses Windows PowerShell to let you list local printers, set the default printer connection, and delete locally defined printers. <\/p>\n<p class=\"CodeBlockScreenedHead\"><strong>SetDefaultPrinterDeletePrinterConnection.ps1<\/p>\n<p><\/strong><\/p>\n<p class=\"CodeBlockScreened\"><font><font face=\"Lucida Sans Typewriter\">Param($computer, $printerPath, [switch]$list, [switch]$setDefault, [switch]$deletePrinter)<\/p>\n<p>Function Get-Printer($computer)<br>{<br><span>&nbsp;<\/span>Get-WmiObject -class Win32_Printer -computer $computer<br>} #end Get-Printer<\/p>\n<p>Function Format-LocalPrinter($printObject)<br>{<br><span>&nbsp;<\/span>Write-Host -foregroundcolor cyan &#8220;Local printers on $computer&#8221;<br><span>&nbsp;<\/span>$printObject | <br><span>&nbsp;<\/span>Format-Table -property deviceID, location, default, comment -autosize -wrap<br>} #end Format-Printer<\/p>\n<p>Function Set-DefaultPrinter($printObject, [string]$printerPath)<br>{<br><span>&nbsp;<\/span>Write-Host -foregroundcolor cyan &#8220;Setting $printerPath to default printer&#8221;<br><span>&nbsp;<\/span>$dp = $printObject |<br><span>&nbsp;<\/span>Where-Object { $_.deviceID -match $printerPath }<br><span>&nbsp;<\/span>$dp.SetDefaultPrinter()<br>} #end Set-DefaultPrinter<\/p>\n<p>Function Remove-Printer($printObject, [string]$printerPath)<br>{<br><span>&nbsp;<\/span>Write-Host -foregroundcolor cyan &#8220;Removing $printerPath&#8221;<br><span>&nbsp; <\/span>$dp = $printObject |<br><span>&nbsp;<\/span>Where-Object { $_.deviceID -match $printerPath }<br><span>&nbsp;<\/span>$dp.psbase.Delete()<br>}<\/p>\n<p>Function Get-SuccessCode($code)<br>{<br><span>&nbsp;<\/span>if($code.ReturnValue -eq 0)<br><span>&nbsp; <\/span>{ Write-Host -foregroundcolor green &#8220;Operation suceeded!&#8221; }<br><span>&nbsp;<\/span>Else<br><span>&nbsp; <\/span>{ Write-Host -foregroundcolor red &#8220;Operation failed with $($code.returnvalue)&#8221; }<br>} #end get-successcode<\/p>\n<p># *** Entry Point to Script ***<br>if($list) { Format-LocalPrinter(Get-Printer($computer)) ; exit }<br>if($setDefault)<br><span>&nbsp;<\/span>{<br><span>&nbsp;&nbsp; <\/span>Get-SuccessCode -code `<br><span>&nbsp;&nbsp; <\/span>(Set-DefaultPrinter -printObject(Get-Printer($computer)) -printerPath $printerPath)<br><span>&nbsp;<\/span>exit<br><span>&nbsp;<\/span>}<br>If($deletePrinter)<br><span>&nbsp;<\/span>{<br><span>&nbsp; <\/span>Remove-Printer -printObject (Get-Printer($computer)) -printerPath $printerPath<br><span>&nbsp; <\/span>exit<br><span>&nbsp;<\/span>}<\/p>\n<p><\/font><\/font><\/p>\n<p class=\"MsoNormal\">In the SetDefaultPrinterDeletePrinterConnection.ps1 script the first thing that you have to do is to create some command-line parameters. These command-line parameters enable you to change the way the script runs when it starts. The first parameter, <strong>&ndash;computer<\/strong>, is used to specify which computer to work with. The <strong>&ndash;printerpath<\/strong> parameter is used to specify the printer. The <strong>&ndash;list<\/strong> switched parameter is used to provide a list of shared printers from the computer specified by the <strong>&ndash;computer<\/strong> parameter. The <strong>&ndash;setDefault<\/strong> switched parameter will set the printer that is specified by the <strong>&ndash;printerpath<\/strong> parameter to the default printer. The <strong>&ndash;deletePrinter<\/strong> switched parameter is used to delete the printer that is named by the <strong>&ndash;printerpath<\/strong> parameter. These command-line parameters are shown here.<\/p>\n<p class=\"CodeBlockScreened\"><font><font face=\"Lucida Sans Typewriter\">Param($computer, $printerPath, [switch]$list, [switch]$setDefault, [switch]$deletePrinter)<\/p>\n<p><\/font><\/font><\/p>\n<p class=\"MsoNormal\">The first function that you come to is the <strong>Get-Printer<\/strong> function. This is the same function that was in <a href=\"http:\/\/blogs.technet.com\/heyscriptingguy\/archive\/2009\/05\/19\/how-can-i-use-wmi-to-add-a-printer-connection-by-using-windows-powershell.aspx\">yesterday&#8217;s script<\/a>. <\/p>\n<p class=\"MsoNormal\">It is used to create the <strong>Win32_Printer<\/strong> WMI management object. To do this, you use the <strong>Get-WmiObject<\/strong> cmdlet. This is seen here: <\/p>\n<p class=\"CodeBlockScreened\"><font><font face=\"Lucida Sans Typewriter\">Function Get-Printer($computer)<br>{<br>Get-WmiObject -class Win32_Printer -computer $computer<br>} #end Get-Printer<\/p>\n<p><\/font><\/font><\/p>\n<p class=\"MsoNormal\">The <strong>Format-LocalPrinter<\/strong> function is used to format the information that is displayed about the local printer. This function is also the same as the function that was used yesterday. The <strong>Format-LocalPrinter<\/strong> function accepts <strong>Win32_Printer<\/strong> WMI management object that was created in the <strong>Get-Printer<\/strong> function as input. Then it uses the <strong>Format-Table<\/strong> cmdlet to display four properties in a table. The <strong>Format-LocalPrinter<\/strong> function is shown here. <\/p>\n<p class=\"CodeBlockScreened\"><font><font face=\"Lucida Sans Typewriter\">Function Format-LocalPrinter($printObject)<br>{<br>Write-Host -foregroundcolor cyan &#8220;Local printers on $computer&#8221;<br>$printObject | <br>Format-Table -property deviceID, location, default, comment -autosize -wrap<br>} #end Format-Printer<\/p>\n<p><\/font><\/font><\/p>\n<p class=\"MsoNormal\">When the SetDefaultPrinterDeletePrinterConnection.ps1 script is run with the <strong>&ndash;computer<\/strong> parameter and the <strong>&ndash;list <\/strong>switch, the <strong>Format-LocalPrinter<\/strong> function will be called. This command line is seen here:<\/p>\n<p class=\"CodeBlockScreened\"><font><font face=\"Lucida Sans Typewriter\">PS bp:&gt; .SetDefaultPrinterDeletePrinterConnection.ps1 -list -computer localhost<\/p>\n<p><\/font><\/font><\/p>\n<p class=\"MsoNormal\">The resulting output from the Format-LocalPrinter function is seen in the following image.<\/p>\n<p class=\"MsoNormal\">\n<p><img decoding=\"async\" title=\"Image of output from Format-LocalPrinter function\" alt=\"Image of output from Format-LocalPrinter function\" src=\"http:\/\/img.microsoft.com\/library\/media\/1033\/technet\/images\/scriptcenter\/qanda\/hsg\/2009\/may\/hey0520\/hsg-05-20-09-01.jpg\" width=\"500\" height=\"185\"><\/p>\n<\/p>\n<p class=\"Fig-Graphic\">Next, the <strong>Set-DefaultPrinter<\/strong> function is created. This function is used to set the printer named in the <strong>&ndash;printerpath <\/strong>parameter to be the default printer on the computer. The <strong>SetdefaultPrinter <\/strong>method is an instance method. This means that it is available when you have a single instance of a printer. To obtain an instance of the <strong>win32_Printer <\/strong>WMI class, the printer object that is stored in the <strong>$printObject <\/strong>variable is piped to the <strong>Where-Object <\/strong>cmdlet. The <strong>Where-Object <\/strong>cmdlet is used to find an instance of a printer that has a value that is contained in the <strong>deviceID <\/strong>property that will match the value supplied through the <strong>&ndash;printerpath <\/strong>parameter. When the match is found, the instance is stored in the <strong>$dp <\/strong>variable. It is this instance that contains the <strong>SetDefaultPrinter<\/strong> WMI method. The <strong>Set-DefaultPrinter<\/strong> function is seen here: <\/p>\n<p class=\"CodeBlockScreened\"><font><font face=\"Lucida Sans Typewriter\">Function Set-DefaultPrinter($printObject, [string]$printerPath)<br>{<br>Write-Host -foregroundcolor cyan &#8220;Setting $printerPath to default printer&#8221;<br>$dp = $printObject |<br>Where-Object { $_.deviceID -match $printerPath }<br>$dp.SetDefaultPrinter()<br>} #end Set-DefaultPrinter<\/p>\n<p><\/font><\/font><\/p>\n<p class=\"MsoNormal\">The command line to set the default printer is seen here. The <strong>computername<\/strong> parameter, the <strong>setdefault<\/strong> switched parameter, and the <strong>printerpath<\/strong> parameters must be supplied. <\/p>\n<p class=\"CodeBlockScreened\"><font><font face=\"Lucida Sans Typewriter\">PS bp:&gt; .SetDefaultPrinterDeletePrinterConnection.ps1 -setDefault -printer testprinter -computer localhost<\/p>\n<p><\/font><\/font><\/p>\n<p class=\"MsoNormal\">When the script is run, the output shown in the following image is displayed. <\/p>\n<p class=\"Fig-Graphic\">\n<p><img decoding=\"async\" title=\"Image of script output\" alt=\"Image of script output\" src=\"http:\/\/img.microsoft.com\/library\/media\/1033\/technet\/images\/scriptcenter\/qanda\/hsg\/2009\/may\/hey0520\/hsg-05-20-09-02.jpg\" width=\"500\" height=\"113\"><\/p>\n<\/p>\n<p class=\"MsoNormal\"><br>It is time create the function that deletes the printer. To do this, create a function named <strong>Remove-Printer<\/strong> and pass it the <strong>Win32_Printer<\/strong> WMI object that is stored in the <strong>$printobject<\/strong> variable and a string that represents the path of the printer to be deleted. Inside the function use the <strong>Write-Host<\/strong> cmdlet to display a message in cyan that indicates which printer is being removed. The <strong>Win32_Printer <\/strong>object that is stored in the <strong>$printobject <\/strong>variable is piped to the <strong>Where-Object<\/strong> cmdlet. Inside the script block for the <strong>Where-Object <\/strong>cmdlet the <strong>deviceID <\/strong>property is examined to find a match for the string that was supplied through the <strong>printerpath <\/strong>parameter. When a match is found, the resulting <strong>Win32_Printer <\/strong>instance is stored in the <strong>$dp <\/strong>variable. To delete the instance, you have to access the underlying <strong>Win32_Printer<\/strong> WMI object by using the <strong>psbase<\/strong> property. As soon as you have the underlying base WMI object, you can call the <strong>delete<\/strong> method. The <strong>Remove-Printer <\/strong>function is shown here. <\/p>\n<p class=\"CodeBlockScreened\"><font><font face=\"Lucida Sans Typewriter\">Function Remove-Printer($printObject, [string]$printerPath)<br>{<br>Write-Host -foregroundcolor cyan &#8220;Removing $printerPath&#8221;<br>$dp = $printObject |<br>Where-Object { $_.deviceID -match $printerPath }<br><span>&nbsp;<\/span>$dp.psbase.Delete()<br>}<\/p>\n<p><\/font><\/font><\/p>\n<p class=\"MsoNormal\">The command line used to delete a printer connection involves passing the <strong>&ndash;deleteprinter<\/strong> switched printer, specifying the printer to delete and the computer upon which to operate. This is shown here: <\/p>\n<p class=\"CodeBlockScreened\"><font><font face=\"Lucida Sans Typewriter\">PS bp:&gt; .SetDefaultPrinterDeletePrinterConnection.ps1 -delete -printer testprinter -computer localhost<br>Removing testprinter<br>PS bp:&gt;<\/p>\n<p><\/font><\/font><\/p>\n<p class=\"MsoNormal\">Now it is time to evaluate the return code from calling the method. This is the same function that was in yesterday&#8217;s script. The return code is passed through the <strong>&ndash;code<\/strong> parameter of the <strong>Get-SuccessCode<\/strong> function. If it is equal to 0, the method call succeeded. If it is equal to something, an error occurred. The <strong>Get-SuccessCode <\/strong>function is seen here:<\/p>\n<p class=\"CodeBlockScreened\"><font><font face=\"Lucida Sans Typewriter\">Function Get-SuccessCode($code)<br>{<br>if($code.ReturnValue -eq 0)<br><span>&nbsp; <\/span>{ Write-Host -foregroundcolor green &#8220;Operation suceeded!&#8221; }<br>Else<br><span>&nbsp; <\/span>{ Write-Host -foregroundcolor red &#8220;Operation failed with $($code.returnvalue)&#8221; }<br>} #end get-successcode<\/p>\n<p><\/font><\/font><\/p>\n<p class=\"MsoNormal\">Now you reach the entry point to the script. The first thing that is performed is to check for the presence of the <strong>&ndash;list <\/strong>switched parameter. If it is found, the <strong>Get-Printer <\/strong>function is called, and the resulting printer object is passed to the <strong>Format-LocalPrinter <\/strong>function that creates a formatted list of all local printers on the target system. The script then exits. This is seen here: <\/p>\n<p class=\"CodeBlockScreened\"><font><font face=\"Lucida Sans Typewriter\">if($list) { Format-LocalPrinter(Get-Printer($computer)) ; exit }<\/p>\n<p><\/font><\/font><\/p>\n<p class=\"MsoNormal\">If the <strong>&ndash;setDefault<\/strong> switched parameter is called, the script calls the <strong>Get-Printer <\/strong>function and retrieves a <strong>printer <\/strong>object. This <strong>printer <\/strong>object is passed to the <strong>Set-DefaultPrinter <\/strong>function, which takes the printer referenced in the <strong>$printerPath<\/strong> variable and sets it to the default printer. The return code from calling the <strong>SetDefaultPrinter <\/strong>method is passed to the <strong>Get-SuccessCode <\/strong>function, which interprets the return value. The script then exits. This line of code is seen here: <\/p>\n<p class=\"CodeBlockScreened\"><font><font face=\"Lucida Sans Typewriter\">if($setDefault)<br>{<br><span>&nbsp;&nbsp; <\/span>Get-SuccessCode -code `<br><span>&nbsp;&nbsp; <\/span>(Set-DefaultPrinter -printObject(Get-Printer($computer)) -printerPath $printerPath)<br>exit<br>}<\/p>\n<p><\/font><\/font><\/p>\n<p class=\"MsoNormal\">You can also use the SetDefaultPrinterDeletePrinterConnection.ps1 script to delete a local printer connection. If the script is run with the <strong>&ndash;deletePrinter<\/strong> switched parameter, the script calls the <strong>Get-Printer<\/strong> function and creates a <strong>printer<\/strong> object. It passes the <strong>printer<\/strong> object to the <strong>Remove-Printer<\/strong> function, which will delete the printer that is named in the<strong> $printerPath<\/strong> variable. This is seen here: <\/p>\n<p class=\"CodeBlockScreened\"><font><font face=\"Lucida Sans Typewriter\">If($deletePrinter)<br>{<br><span>&nbsp; <\/span>Remove-Printer -printObject (Get-Printer($computer)) -printerPath $printerPath<br><span>&nbsp; <\/span>exit<br>}<\/p>\n<p><\/font><\/font><\/p>\n<p class=\"MsoNormal\">&nbsp;<\/p>\n<p class=\"MsoNormal\">Well, BP, we have successfully set the default printer, deleted printer connections, and obtained a listing of local printers. Along the way, we used a couple of functions that we had created previously. Join us tomorrow as we continue with Printer Week. Until then, peace. <\/p>\n<p class=\"MsoNormal\"><font size=\"3\"><font face=\"Times New Roman\"><\/font><\/font>&nbsp;<\/p>\n<p class=\"MsoNormal\"><font size=\"3\"><strong><font face=\"arial,helvetica,sans-serif\">Ed Wilson and Craig Liebendorfer, Scripting Guys<\/p>\n<p><\/font><\/strong><\/font><\/p>\n<p>&nbsp;<\/p>\n<\/h2>\n","protected":false},"excerpt":{"rendered":"<p>Hey, Scripting Guy! Well it finally happened. Our budget request for new printers was approved. We have gotten them unboxed, distributed, and hooked up to the LAN. We have even downloaded the latest drivers from the Internet, and updated the firmware on several of the printers. The drivers are installed on the print servers, and [&hellip;]<\/p>\n","protected":false},"author":595,"featured_media":87096,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"_acf_changed":false,"footnotes":""},"categories":[1],"tags":[445,404,3,45],"class_list":["post-53713","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-scripting","tag-client-side-printing","tag-printing","tag-scripting-guy","tag-windows-powershell"],"acf":[],"blog_post_summary":"<p>Hey, Scripting Guy! Well it finally happened. Our budget request for new printers was approved. We have gotten them unboxed, distributed, and hooked up to the LAN. We have even downloaded the latest drivers from the Internet, and updated the firmware on several of the printers. The drivers are installed on the print servers, and [&hellip;]<\/p>\n","_links":{"self":[{"href":"https:\/\/devblogs.microsoft.com\/scripting\/wp-json\/wp\/v2\/posts\/53713","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/devblogs.microsoft.com\/scripting\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/devblogs.microsoft.com\/scripting\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/devblogs.microsoft.com\/scripting\/wp-json\/wp\/v2\/users\/595"}],"replies":[{"embeddable":true,"href":"https:\/\/devblogs.microsoft.com\/scripting\/wp-json\/wp\/v2\/comments?post=53713"}],"version-history":[{"count":0,"href":"https:\/\/devblogs.microsoft.com\/scripting\/wp-json\/wp\/v2\/posts\/53713\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/devblogs.microsoft.com\/scripting\/wp-json\/wp\/v2\/media\/87096"}],"wp:attachment":[{"href":"https:\/\/devblogs.microsoft.com\/scripting\/wp-json\/wp\/v2\/media?parent=53713"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/devblogs.microsoft.com\/scripting\/wp-json\/wp\/v2\/categories?post=53713"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/devblogs.microsoft.com\/scripting\/wp-json\/wp\/v2\/tags?post=53713"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}