如何将PSObject强制转换为SecureString。无法隐式转换

时间:2016-05-26 17:24:02

标签: c# powershell runspace

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

1 个答案:

答案 0 :(得分:2)

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

mgSettings.Password = result.BaseObject as SecureString;