在 C# 代码中使用 PSCredentials

Using PSCredentials in C# code

我正在编写一个二进制 cmdlet,我想接受一个 PSCredential 参数以便使用提升的凭据。

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

这方面似乎明显缺乏文档 - 我所能找到的只是如何从 C# 执行 PowerShell cmdlet,这不是我想要做的。

我下载了 SimpleImpersonation nuget 包以避免自己进行 Windows 模拟。

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

当我检查 System.Security.Principal.WindowsIdentity.GetCurrent().Name 时,用户是正确的,但是当我执行命令(例如 ServerManager.OpenRemote(computerName))时,我收到 UnauthorizedAccessException。如果我 运行 来自 PowerShell 实例的此代码 运行 宁作为所需用户,cmdlet 将完美执行。

关于如何在 C# 二进制 cmdlet 中使用 PSCredential 是否有任何线索?

我不知道为什么在线文档这么少。正如我所怀疑的那样,我需要使用模拟来完成此操作。这似乎涉及很多管道,see here

经过更多调查后,有一个名为 SimpleImpersonation 的不错的 nuget 包。

使用:

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

我能做到:

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

这允许我以模拟用户的身份 运行 命令。 LogonUser() 使用用户名和 SecureString 密码。

这适用于 ServiceController 调用,但 ServerManager 仍然抛出 COM 未经授权的异常。我设法找到 this post 说不使用 OpenRemote() 而是使用 ctor 重载。以下代码有效:

using (ServerManager serverManager = new ServerManager(@"\server\c$\windows\system32\inetsrv\config\applicationHost.config"))
{
    ApplicationPoolCollection appPool = serverManager.ApplicationPools;
    Console.WriteLine(appPool.Count);
}