Powershell in c# and permissions

2.5k Views Asked by At

I am running PowerShell scripts from a Windows service running as SYSTEM account. To increase rights I am letting users select a user that I later impersonate the whole thread as using LogonUser method.

This works so that I can access network drives and when I try to print the current user in PowerShell that works too.

But I have a case when it does not work:

One example is a user trying to load Exchange snapin and run cmdlet: Get-MailboxPermission

Then he get error: The term 'Get-MailboxPermission' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again. The term 'Get-MailboxPermission' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again.

I am guessing that this is permissions issue and I wonder if there is anything else that needs to be changed to RunSpace etc to get the increased permissions? Any other ideas?

1

There are 1 best solutions below

2
On

Which PowerShell version?

Looks like you don't have the exchange snapin added. Try running this command before:

Add-PSSnapin Microsoft.Exchange.Management.PowerShell.Admin

or, via code, in the runspace initialization, use this code:

RunspaceConfiguration rsConfig = RunspaceConfiguration.Create();
PSSnapInException snapInException = null;
PSSnapInInfo info = rsConfig.AddPSSnapIn("Microsoft.Exchange.Management.PowerShell.Admin", out snapInException);
Runspace myRunSpace = RunspaceFactory.CreateRunspace(rsConfig);
myRunSpace.Open(rsConfig);

read this article for additional info: http://msdn.microsoft.com/en-us/library/exchange/bb332449(v=exchg.80).aspx