如何将 PSObject 转换为 SecureString。不能隐式转换

How to cast PSObject to SecureString. Cannot implicitly convert

假设我在 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;
    }
}

我还没有对此进行测试,但请尝试使用基础对象然后进行转换:

mgSettings.Password = result.BaseObject as SecureString;