Tester101
Tester101

Reputation: 8172

Is it possible to use WMI in a Windows service?

I'm writing a simple service to set the default printer based on where I'm connected, but I'm having trouble using WMI in my service. The more I think about it the less I think it's possible to do what I'm trying to do; as a service is not associated with a particular user, but I thought I would ask about it anyway in case my suspicions are wrong.

Here is what I'm doing.

  1. Service subscribes to NetworkChange.NetworkAvailabilityChanged event.
  2. When event is received query WMI SELECT * FROM Win32_Printer WHERE Network=true.
  3. Loop through the ManagementObjectCollection and check the status of each printer.
  4. If the printer is connected call ManagementObject.InvokeMethod("SetDefaultPrinter",null)

When I check the Security event log I noticed Failure Audit events "Unknown username or bad password", which I'm assuming is because I did not explicitly supply that information.

Is there a way to do this without specifying a username and password, or are credentials required for security purposes?

Upvotes: 0

Views: 1662

Answers (3)

Robert
Robert

Reputation: 3408

I know this is an old question but i feel the existing answer doesn't quite provide a manageable solution.

As pointed out to effect a users default printer selection you need to be authenticated as that user and whilst it is possible to set a windows service to logon as a specific user a better solution would be to ...

Create a winforms program using a hidden form and launch it when the user logs on using Task Scheduler.

This way the PC can be used by many users and benefit from the application without having to change the service logon settings.

I suggested a winforms application as it has a low entry bar, you can use any other kind of invisible from a UI perspective project type.

Upvotes: 2

Serguei
Serguei

Reputation: 2958

The service must run as some user, for example NETWORK SERVICE, LOCAL SERVICE or SYSTEM. You need to make sure the given account has permission to do what you want. To change the permission of a deployed service on Windows go to Start > Administrative Tools > Services then you can change the service account for a given service.

Upvotes: 1

phillip
phillip

Reputation: 2738

you should use linqtowmi for this it works great!

Upvotes: -1

Related Questions