Get-WindowsFeature when running as service

Running this bit of PowerShell from C#:

import-module ServerManager ; Get-WindowsFeature | Where-Object {$_.Installed -eq 'True'} | Select Name,DisplayName,FeatureType

It’s running as a service user, runs fine from command line as that user, but when running in the context of a service it fails miserably.

Does the service user need particular permissions or configuration to be able to do this when running as a service?

Error from the ServiceManager.log is this:

3440: 2014-12-05 09:10:34.607 [ExceptionHandler] Error (Id=0) An unexpected exception was found:
System.UnauthorizedAccessException: Retrieving the COM class factory for component with CLSID {BA126AD1-2166-11D1-B1D0-00805FC1270E} failed due to the following error: 80070005 Access is denied. (Exception from HRESULT: 0x80070005 (E_ACCESSDENIED)).
   at Microsoft.Windows.ServerManager.DirectResult.GetLocalNetworkAdapterInfo()
   at Microsoft.Windows.ServerManager.DirectResult.InitializeNetworkAdapterInfo()
   at Microsoft.Windows.ServerManager.DirectResult.PopulateData()
   at Microsoft.Windows.ServerManager.ServerManagerModel.InternalRefreshDirectResult(Object state)

It’s possible that the underlying COM object is looking for specific elements of a user profile, which a service won’t have (and can’t be made to have). It isn’t a permission thing, it’s a context thing. You might not be able to force a service to do that.

That said, anything PowerShell can do, C# can do. Given that you know the COM class ID (from the error), you might be able to instantiate it and work with it directly from C#.

Ended up using gwmi win32_serverfeature instead. Not as much information, but it will do for 2008 boxes.