首页 > 解决方案 > 在 C# 中使用“New-Object”cmdlet

问题描述

我正在尝试在我一直在处理的 C# 程序中运行一些 Powershell cmdlet。

我一直在尝试运行的 cmdlet 如下:

$cred = New-Object System.Management.Automation.PSCredential (user, (ConvertTo-SecureString pass –ASPlainText –Force)); 

我在 C# 程序中所做的如下:

string user = textBox1.Text;
            string pass = textBox2.Text;



            PowerShell ps = PowerShell.Create();
            ps.AddCommand("New-Object");
            ps.AddArgument("System.Management.Automation.PSCredential ("+user+", (ConvertTo-SecureString "+pass+" –ASPlainText –Force))");
            var cred = ps.Invoke();

但是当我这样做时,我收到以下错误提示:

A constructor was not found. Cannot find an appropriate constructor for type System.Management.Automation.PSCredential (user, (ConvertTo-SecureString pass –ASPlainText –Force)).

所以我的问题是,如何从我的 C# 程序运行这个 Powershell cmdlet,并将结果存储在 C# 程序内的变量中?

谢谢!

标签: c#powershell

解决方案


这可以在不调用 powershell 的情况下完成。这是否有用取决于你在做什么。

var user = "username";
var pass = new System.Security.SecureString();
foreach (char c in "password")
{
    pass.AppendChar(c);
}
var cred = new System.Management.Automation.PSCredential(user, pass);

推荐阅读