Freigeben über


Get Print Jobs using WMI and ManagmentObjects

I found a way to get the print jobs from the spoiler using Management objects and WMI

public static void GetPrintJobs()

{

    string searchQuery = "SELECT * FROM Win32_PrintJob";

    ManagementObjectSearcher searchPrintJobs = new ManagementObjectSearcher(searchQuery);

    ManagementObjectCollection prntJobCollection = searchPrintJobs.Get();

    foreach (ManagementObject prntJob in prntJobCollection)

    {

        try

        {

            string document = prntJob.Properties["Document"].Value.ToString();

            string color = prntJob.Properties["Color"].Value.ToString();

            string host = prntJob.Properties["HostPrintQueue"].Value.ToString();

            string owner = prntJob.Properties["Owner"].Value.ToString();

            int id = int.Parse(prntJob.Properties["JobId"].Value.ToString());

            int pages = int.Parse(prntJob.Properties["TotalPages"].Value.ToString());

            Console.WriteLine("{0} Document '{1}', pages {2} {3}, sent by {4}\\{5}", id, document, pages, color, host, owner);

        }

        catch (Exception ex)

        {

            Console.WriteLine("Exception getting print jobs: " + ex);

        }

    }

}

one note about this code, it'll only work in Vista/LHS, to make it work in win xp/2k3 just don't ask for the property Color which aparently does not exist in previous versions of Windows. 

you can find more information about the properties of the Win32_PrintJob class here https://msdn2.microsoft.com/en-us/library/aa394370.aspx

 and a little more about WMI https://msdn2.microsoft.com/en-us/library/aa394582.aspx which in my opinion is a great way to manage windows, but it is kind of slow

Comments