我正在编写二进制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
,有什么线索吗?
1条答案
按热度按时间wlp8pajw1#
我不知道为什么网上的文档这么少,因为我怀疑我需要使用模拟来完成它,似乎有很多管道涉及到这个,see here。
经过更多的研究,有一个很好的nuget包称为SimpleImpersonation。
使用:
我可以这样做:
这允许我以模拟用户的身份运行命令。
LogonUser()
接受用户名和SecureString
密码。这对
ServiceController
调用很有效,但是ServerManager
仍然抛出COM未授权异常。我设法找到了this post,它说不要使用OpenRemote()
,而是使用一个ctor重载。下面的代码有效: