假设我在 PowerShell 中使用以下内容创建加密文件:
$PWD = Read-host "Enter Password" -assecurestring
$PWD | ConvertFrom-SecureString -key (1..16)| out-file encrypted.txt
在 C# 中,我使用 PowerShell 运行空间来读取加密文件并转换为 SecureString:
using (PowerShell powershell = PowerShell.Create())
{
powershell.AddScript("get-content c:\\tools\\scripts\\encrypted.txt | convertTo-SecureString -key (1..16)");
foreach (PSObject result in powershell.Invoke())
{
Console.WriteLine(PSObject); //This returns System.Security.SecureString
Console.WriteLine(result.GetType()); //This returns System.Security.SecureString
ManagementGroupConnectionSettings mgSettings = new
ManagementGroupConnectionSettings(serverName);
mgSettings.UserName = name;
mgSettings.Domain = userDomain;
//I am trying to pass this to a field that accepts SecureString
//However there is an error "Cannot implicitly convert type 'System.Management.Automation.PSObject' to 'System.Security.SecureString'
mgSettings.Password = result;
}
}