【问题标题】:Using PSCredentials in C# code在 C# 代码中使用 PSCredentials
【发布时间】:2017-01-31 17:15:57
【问题描述】:

我正在编写一个二进制 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 有任何线索吗?

【问题讨论】:

    标签: c# powershell impersonation


    【解决方案1】:

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

    经过进一步调查,有一个不错的 nuget 包,名为 SimpleImpersonation

    使用:

    [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);
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-10-09
      • 2022-01-04
      • 1970-01-01
      • 2017-07-18
      • 2016-01-06
      相关资源
      最近更新 更多