首页 > 解决方案 > 如何在单击按钮时请求 SecureString 密码以传递给 Power Shell 进程

问题描述

我有一个通过 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)时如何运行此操作。我觉得我几乎什么都懂,但我错过了一些非常重要的东西。

标签: c#.netpowershellpasswords

解决方案


感谢所有的建议。

通过使用“Get-Credential”启动 Power Shell 脚本,我能够绕过所有这些,这将提示用户输入密码。更容易(也更安全)。


推荐阅读