首页 > 解决方案 > 使用 ProcessStartInfo 从 C# 到 PowerShell 的 SecureString 密码

问题描述

在我的 C# (.net core 3.1) 代码中,我想启动一个带有多个参数的 PowerShell 脚本。

我创建 ProcessStartInfo 的代码部分如下所示:

var processStartInfo = new ProcessStartInfo()
        {
            FileName = "powershell.exe",
            Arguments = "-NoProfile -NonInteractive -File " + powerShellScriptPath + " -login " + login + " -password " + password + " -server " + server,
            UseShellExecute = false,
            RedirectStandardInput = true,
            RedirectStandardOutput = true,
            RedirectStandardError = true,
            CreateNoWindow = true,
        };

我希望密码是安全的,因为我在 PowerShell 中有一个警告,告诉我使用安全字符串。

目前我的密码只是一个字符串,在我使用的 powershell 脚本中:

ConvertTo-SecureString $password -AsPlainText -Force

有没有办法在 C# 代码中转换为安全字符串并将安全字符串密码直接传递给 powershell 脚本?

谢谢

标签: c#powershell

解决方案


正如评论中所建议的,我不再使用 SecureString,现在我使用标准输入,这是 C# 代码:

// your init code

//Create the process
var processStartInfo = new ProcessStartInfo()
{
    FileName = "powershell.exe",
    Arguments = EscapeCommandLineArguments(cmdLine),
    UseShellExecute = false,
    RedirectStandardInput = true,
    RedirectStandardOutput = true,
    RedirectStandardError = true,
    CreateNoWindow = true,
};

var process = new Process()
{
    StartInfo = processStartInfo,
};

// your code including process.start

// Write the password to the standard input
process.StandardInput.WriteLine(password);

//end of your code

在 ps1 脚本中我取回密码:

# Read the password on the standard input    
[string]$pass = Read-Host
# do what you want with the pass and then erase it will $null
$pass = $null

我希望它会帮助你们中的一些人。


推荐阅读