Search code examples
c#.netpowershellwindows-server-2012

Passing logged in user credentials to Powershell cmdlet


I have a Windows Service running (service is running as "NT AUTHORITY\SYSTEM") on Windows 2012 Server. This service needs to get a list of VMs from a remote machine. It executes cmdlet equivalent of "get-vm -ComputerSystem RemoteServer1". Currently logged in user is 'Administrator' who has access to call get-vm on the remote machine. However, "NT AUTHORITY\SYSTEM" does not have permission to call get-vm on the remote machine. Below is the code.

PowerShell psStopVM = PowerShell.Create();
psStopVM.AddCommand("Stop-VM");
psStopVM.AddParameter("Name", vmName);
psStopVM.AddParameter("ComputerName", VMHost);
psStopVM.AddParameter("Force", true);

psStopVM.Invoke(); //exception occurs here

When I run this code, I get the following error. Microsoft.HyperV.PowerShell.VirtualizationOperationFailedException: You do not have permission to perform the operation. Contact your administrator if you believe you should have permission to perform this operation. ---> System.UnauthorizedAccessException: Access is denied. (Exception from HRESULT: 0x80070005 (E_ACCESSDENIED))

How can I pass the credentials of logged in user (Administrator) in the C# code such that I can successfully call get-vm cmdlet from C# Code?


Solution

  • You can either use Invoke-Command and create an ad hoc session with admin creds to invoke you command with sufficient privileges or, if you need to run more than one command, you can create a remote runspace with admin credentials and execute your commands in that runspace. This will require WinRM service configured and running.

    You other option, and I would go that route, is to run the service under identity of the admin user or a dedicated account with sufficient privileges instead of NT AUTHORITY\SYSTEM. This way you do not store your admin creds insecurely with your code, not naming other consequences of hard-coding creds.