【发布时间】:2019-09-09 18:52:52
【问题描述】:
我有一个通过 Power Shell 运行命令的应用程序。我知道如何以不同的用户身份运行它,但我完全不知道如何获取密码。我想每次都提示用户输入密码(我只希望应用程序最多使用一次),所以我不需要存储它。我了解我需要将密码创建为安全字符串。最重要的是,我希望它在单击按钮时运行,但我不知道如何调用它。这是我目前所拥有的:
class Credentials
{
private static SecureString MakeSecureString(string text)
{
SecureString secure = new SecureString();
foreach (char c in text)
{
secure.AppendChar(c);
}
return secure;
}
public static void RunAs(string path, string username, string password)
{
try
{
Process process = new Process();
process.StartInfo.FileName = "powershell.exe";
process.StartInfo.UserName = "adminaccount@account.com";
process.StartInfo.Password = MakeSecureString(password);
process.StartInfo.CreateNoWindow = false;
process.StartInfo.RedirectStandardInput = true;
process.StartInfo.RedirectStandardOutput = true;
process.StartInfo.RedirectStandardError = true;
process.StartInfo.UseShellExecute = false;
process.Start();
process.StandardInput.WriteLine(" Some Power Shell Script");
process.StandardInput.Flush();
process.StandardInput.Close();
process.WaitForExit();
Console.WriteLine(process.StandardOutput.ReadToEnd());
Console.WriteLine(process.StandardError.ReadToEnd());
Console.Read();
}
catch (Win32Exception w32E)
{
// The process didn't start.
Console.WriteLine(w32E);
}
}
}
// Later invoked in this button click handler
private void Button_Click(object sender, EventArgs e)
{
Credentials.SecureString();
Credentials.RunAs();
}
单击按钮时如何运行此按钮 (Button_Clicked)。我觉得我几乎什么都懂,但我错过了一些非常重要的东西。
【问题讨论】:
-
您的
Credentials类没有SecureString方法(Button_Click中的第一行)。
标签: c# .net powershell passwords