0

I have function like this (test.ps1):

function HLS {
    Write-Host 'Hello, World!'
}

I execute this commands in PS window:

$expression = Get-Content -Path .\test.ps1
$commandBytes = [System.Text.Encoding]::Unicode.GetBytes($expression)
$encodedCommand = [Convert]::ToBase64String($commandBytes)
powershell -EncodedCommand $encodedCommand

It does not give me any output, which is good because i would need to execute this function. After trying to execute this command:

PS C:\truncated> HLS

It gives me error:

HLS : The term 'HLS' is not recognized as the name of a cmdlet, function, script file, or operable program.

Does anyone know how to execute function that is passed as -EncodedCommand parameter?

4
  • 1
    Why not simply dot source your .\test.ps1 ?? By running powershell -EncodedCommand $encodedCommand, the script will use its own environment and the caller script will have no knowledge about that. Commented Mar 19, 2022 at 12:56
  • Becasue I need to execute it as base64 without touching the disk Commented Mar 19, 2022 at 12:59
  • ..but you are touching the disk here: $expression = Get-Content -Path .\test.ps1 Commented Mar 19, 2022 at 13:00
  • IT is just for now, later the base64 will be embedded in command. $expression = Get-Content -Path .\test.ps1 is just temporary Commented Mar 19, 2022 at 13:00

1 Answer 1

2

Continuing from our comments.

If what you want is to embed just the base64 packed code block in your script, you should not use powershell -EncodedCommand $encodedCommand, because that will simply run in its own environment and your main script will know nothing about the function defined there.

For that you can use Invoke-Expression, but do read the Warning

$expression     = Get-Content -Path .\test.ps1
$commandBytes   = [System.Text.Encoding]::Unicode.GetBytes($expression)
$encodedCommand = [Convert]::ToBase64String($commandBytes)

# output the $encodedCommand so you can use it in the main script later:
$encodedCommand

Result:

ZgB1AG4AYwB0AGkAbwBuACAASABMAFMAIAB7AA0ACgAgACAAIAAgAFcAcgBpAHQAZQAtAEgAbwBzAHQAIAAnAEgAZQBsAGwAbwAsACAAVwBvAHIAbABkACEAJwANAAoAfQA=

Next, in your main script, use the base64 value of $encodedCommand directly:

$encodedCommand = 'ZgB1AG4AYwB0AGkAbwBuACAASABMAFMAIAB7AA0ACgAgACAAIAAgAFcAcgBpAHQAZQAtAEgAbwBzAHQAIAAnAEgAZQBsAGwAbwAsACAAVwBvAHIAbABkACEAJwANAAoAfQA='
Invoke-Expression ([System.Text.Encoding]::Unicode.GetString([convert]::FromBase64String($encodedCommand)))
# now the function is known and can be used
HLS

Result:

Hello, World!
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.