hsimah hsimah - 2 months ago 35
C# Question

Using PSCredentials in C# code

I am writing a binary cmdlet and I would like to accept a

PSCredential
parameter in order to use elevated credentials.

[Parameter]
public PSCredential Credential { get; set; }


I want to create an IIS site using this credential. How do I run commands as this user? Mainly looking at
ServerManager
.

Answer

I'm not sure why this has so little documentation online. As I suspected I needed to use impersonation to accomplish this. There seems to be a lot of plumbing involved with this, see here.

After some more investigation there's a nice nuget package called SimpleInjector.

Using:

[Parameter]
public PSCredential Credential { get; set; }

I can do this:

using (Impersonation.LogonUser("GLOBAL", Credential.UserName, Credential.Password, LogonType.Interactive))

This allows me to run commands as the impersonated user. LogonUser() takes the username and SecureString password.