简体   繁体   中英

How to cast PSObject to SecureString. Cannot implicitly convert

Let's say I am using the following in PowerShell to create an encrypted file:

$PWD = Read-host "Enter Password" -assecurestring
$PWD | ConvertFrom-SecureString -key (1..16)| out-file encrypted.txt

In C# I am using a PowerShell runspace to read the encrypted file and convert to a 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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM