powershell 在C#代码中使用PS凭据

jhkqcmku  于 2023-02-04  发布在  Shell
关注(0)|答案(1)|浏览(110)

我正在编写二进制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,有什么线索吗?

wlp8pajw

wlp8pajw1#

我不知道为什么网上的文档这么少,因为我怀疑我需要使用模拟来完成它,似乎有很多管道涉及到这个,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);
}

相关问题