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; }
There seems to be a distinct lack of documentation for this - all I can find is how to execute PowerShell cmdlets from C#, which is not what I wish to do.
I downloaded the SimpleImpersonation nuget package to avoid doing the Windows impersonation myself.
using (Impersonation.LogonUser("GLOBAL", "last.first", "mypassword", LogonType.Interactive))
{
foreach (ServerInfo server in Targets)
ProcessRecord();
}
When I check System.Security.Principal.WindowsIdentity.GetCurrent().Name the user is correct, but when I execute a command (eg ServerManager.OpenRemote(computerName)) I receive an UnauthorizedAccessException. If I run this code from a PowerShell instance running as the desired user the cmdlet executes flawlessly.
Does anyway have any clues as to how to utilise a PSCredential in a C# binary cmdlet?