windowspowershellshellcommand-line

Cannot convert the value of type "System.String" to type "System.Security.SecureString" but only in PS 7.4.6 but not in PS 5.1


I made a script to unlock bitlocker volumes using the password manager autotype feature instead of the clipboard. It uses gsudo and needs some features available only in 7.4.

$DriveLetter = Read-Host "Drive letter"
$DriveLetter = ($DriveLetter + ":")
$EncUserCredential = Read-Host "Enter Password" -AsSecureString | ConvertFrom-SecureString
gsudo pwsh.exe -CommandWithArgs '`$parm1 = ConvertTo-SecureString -String `$args[1]; Unlock-Bitlocker -MountPoint `$args[0] -Password `$parm1' $DriveLetter $EncUserCredential

When I run the script directly in a 7.4.6 shell I get:

Drive letter: w
Enter Password: ********************
Unlock-BitLocker: Cannot process argument transformation on parameter 'Password'. Cannot convert the value of type "System.String" to type "System.Security.SecureString".

Conversely, if I run it in 5.1 (7.4 is invoked later in the script) it works, why? This forces me to keep 5.1 as the default powershell for my terminal, not a big deal but still... Also, the policy for unsigned scripts is only applied to 5.1, it seems to me that this makes the setting somewhat less relevant.


Solution

  • From a PowerShell session, gsudo offers convenient syntax for invoking PowerShell commands directly, using a script block ({ ... }) and optional arguments, which can be passed as an array to the -Args parameter:

    gsudo { 
      $parm1 = ConvertTo-SecureString -String $args[1]
      Unlock-Bitlocker -MountPoint $args[0] -Password $parm1
    } -Args $DriveLetter, $EncUserCredential
    

    Compared to your attempt to call pwsh, the PowerShell (Core) 7 CLI, explicitly, the above is:


    As for what you tried: