hsimah hsimah - 1 month ago 11x
C# Question

Using PSCredentials in C# code

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

parameter in order to use elevated credentials.

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


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.


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.