SetDefaultPrinter using Pinvoke and Powershell

$code = @'
using System;
using System.Runtime.InteropServices;


namespace ChangeDefaultPrinter
{
    public class Program
    {
        
        [DllImport("Winspool.drv", CharSet=CharSet.Auto, SetLastError=true)]
        private static extern bool SetDefaultPrinter(string printerName);
        public static bool Run(string PrinterName)
        {
            bool default_result = SetDefaultPrinter(PrinterName);		
			return default_result;
        }
    }
}
'@

cls
Add-Type -TypeDefinition $code -Language CSharp  

#Set Default Printer - for network printers use \\PrintServer\PrintQueue

if(!([ChangeDefaultPrinter.Program]::Run("Canon iR-ADV C5045/5051 PCL5c")))
{
	throw (New-Object componentmodel.win32Exception )
}

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s