c# - 在 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# 程序内的变量中?
谢谢!
解决方案
这可以在不调用 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);
推荐阅读
- android - Ionic LoadingController 中的 HTML5 视频加载
- javascript - 有没有办法恢复 Vanilla JavaScript 中的 preventDefault 方法?
- jvm - 为什么 Jasmin 不喜欢这个汇编代码?
- python-3.x - 代码优化 - 按月比较两个日期时间列并创建一个新列太慢
- html - CSS:无法将圆角应用于自定义输入字段(在其他字段上工作)
- ssl - 如何从证书(.cer)、证书链(.p7b)和密钥(.key 和 .pem)生成 keystore.p12
- html - 锚链接转到未找到的页面而不是同一页面中的部分
- linux - 异步 posix_fallocate()?
- java - 有没有办法获得最大点的对象
- java - 为什么 CascadeType.MERGE 删除数据库中的记录