Using PSCredentials in C# code
<p>I am writing a binary cmdlet and I would like to accept a <code>PSCredential</code> parameter in order to use elevated credentials.</p>

<pre><code>[Parameter]
public PSCredential Credential { get; set; }
</code></pre>

<p>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.</p>

<p>I downloaded the <code>SimpleImpersonation</code> nuget package to avoid doing the Windows impersonation myself.</p>

<pre><code>using (Impersonation.LogonUser("GLOBAL", "last.first", "mypassword", LogonType.Interactive))
{
    foreach (ServerInfo server in Targets)
        ProcessRecord();
}
</code></pre>

<p>When I check <code>System.Security.Principal.WindowsIdentity.GetCurrent().Name</code> the user is correct, but when I execute a command (eg <code>ServerManager.OpenRemote(computerName)</code>) I receive an <code>UnauthorizedAccessException</code>. If I run this code from a PowerShell instance running as the desired user the cmdlet executes flawlessly.</p>

<p>Does anyway have any clues as to how to utilise a <code>PSCredential</code> in a C# binary cmdlet?</p>