PowerTip: Encode String and Execute with PowerShell


Summary: Learn how to encode a string into base64 and execute it with Windows PowerShell.

Hey, Scripting Guy! Question How can I encode a string into base64 and then run it via Windows PowerShell?

Hey, Scripting Guy! Answer Use these commands:

$string = {(Get-WindowsFeature).Where{$PSItem.Installed}}.ToString()

$encodedcommand = [Convert]::ToBase64String([Text.Encoding]::Unicode.GetBytes($string))

powershell.exe -EncodedCommand $encodedcommand

Comments (3)

  1. PetSerAl says:

    IMHO, if you running powershell.exe from PowerShell, then it is much easier to pass ScriptBlock to -Command parameter. In that case PowerShell will handle encoding for you:
    $command = {(Get-WindowsFeature).Where{$PSItem.Installed}}
    powershell.exe -Command $command

  2. Jens Fiederer says:

    Using Powershell 5.0, I get errors:

    powershell.exe : Get-WindowsFeature : The target of the specified cmdlet cannot be a Windows

    At line:1 char:1
    + powershell.exe -EncodedCommand $encodedcommand
    + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo : NotSpecified: (Get-WindowsFeat…be a Windows
    :String) [], RemoteException
    + FullyQualifiedErrorId : NativeCommandError

    powershell.exe : client-based operating system.
    …etc…

  3. Jens Fiederer says:

    (that was using Windows 8.1)

Skip to main content