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?
CodePudding user response:
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!