Search code examples
powershellpowershell-3.0

PowerShell one-liner - How to


Let's have this example PS code:

$Secr = $Encrypted | ConvertTo-SecureString -Key $Key
$BSTR = [System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($Secr)
$Decrypted = [System.Runtime.InteropServices.Marshal]::PtrToStringAuto($BSTR)

The variables $Secr and $BSTR are used just once.

Is it possible to put it into a one-liner to avoid those temporary variables?

I tried to eliminate $Secr, but this does not work:

$BSTR = [System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($Encrypted | ConvertTo-SecureString -Key $Key)
$Decrypted = [System.Runtime.InteropServices.Marshal]::PtrToStringAuto($BSTR)

Another example is:

$GetKey = Get-Content "C:\temp\AESKey.AES.Key"
$Text = "Test Message"
$Encrypted = ConvertTo-SecureString $Text -AsPlainText -Force | ConvertFrom-SecureString -key $GetKey

Is it possible to eliminate $GetKey variable?

How to make it work? What is the correct syntax?


Solution

  • Use either the grouping operator (...) or the subexpression operator $(...) to evaluate your command pipelines in place of the variable expressions:

    $Decrypted = [System.Runtime.InteropServices.Marshal]::PtrToStringAuto(
      [System.Runtime.InteropServices.Marshal]::SecureStringToBSTR(
        ($Encrypted | ConvertTo-SecureString -Key (Get-Content "C:\temp\AESKey.AES.Key"))
      )
    )
    

    (You can remove the linebreaks for a "true oneliner", only introduced for readability)

    Same treatment for the second example - simply substitute the variable expression with the appropriate pipelines nested in the (...) grouping operator - or, in the case of simpler literal expressions like strings, skip the operator completely:

    $Encrypted = ConvertTo-SecureString "Test Message" -AsPlainText -Force | ConvertFrom-SecureString -key (Get-Content "C:\temp\AESKey.AES.Key")
    

    See the Special Operators section of the about_Operators help topic for more information