如何执行Base64编码的powershell函数?
How to execute Base64 encoded powershell function?
我有这样的功能 (test.ps1):
function HLS {
Write-Host 'Hello, World!'
}
我在 PS window:
中执行此命令
$expression = Get-Content -Path .\test.ps1
$commandBytes = [System.Text.Encoding]::Unicode.GetBytes($expression)
$encodedCommand = [Convert]::ToBase64String($commandBytes)
powershell -EncodedCommand $encodedCommand
它没有给我任何输出,这很好,因为我需要执行这个函数。
尝试执行此命令后:
PS C:\truncated> HLS
它给我错误:
HLS : The term 'HLS' is not recognized as the name of a cmdlet, function, script file, or operable program.
有人知道如何执行作为 -EncodedCommand 参数传递的函数吗?
继续我们的评论。
如果您只想在脚本中嵌入 base64 打包代码块,则不应使用 powershell -EncodedCommand $encodedCommand
,因为那样只会 运行 在它自己的环境中,您的主脚本将对那里定义的函数一无所知。
为此您可以使用 Invoke-Expression
,但请务必阅读 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
结果:
ZgB1AG4AYwB0AGkAbwBuACAASABMAFMAIAB7AA0ACgAgACAAIAAgAFcAcgBpAHQAZQAtAEgAbwBzAHQAIAAnAEgAZQBsAGwAbwAsACAAVwBvAHIAbABkACEAJwANAAoAfQA=
接下来,在您的主脚本中,直接使用 $encodedCommand 的 base64 值:
$encodedCommand = 'ZgB1AG4AYwB0AGkAbwBuACAASABMAFMAIAB7AA0ACgAgACAAIAAgAFcAcgBpAHQAZQAtAEgAbwBzAHQAIAAnAEgAZQBsAGwAbwAsACAAVwBvAHIAbABkACEAJwANAAoAfQA='
Invoke-Expression ([System.Text.Encoding]::Unicode.GetString([convert]::FromBase64String($encodedCommand)))
# now the function is known and can be used
HLS
结果:
Hello, World!
我有这样的功能 (test.ps1):
function HLS {
Write-Host 'Hello, World!'
}
我在 PS window:
中执行此命令$expression = Get-Content -Path .\test.ps1
$commandBytes = [System.Text.Encoding]::Unicode.GetBytes($expression)
$encodedCommand = [Convert]::ToBase64String($commandBytes)
powershell -EncodedCommand $encodedCommand
它没有给我任何输出,这很好,因为我需要执行这个函数。 尝试执行此命令后:
PS C:\truncated> HLS
它给我错误:
HLS : The term 'HLS' is not recognized as the name of a cmdlet, function, script file, or operable program.
有人知道如何执行作为 -EncodedCommand 参数传递的函数吗?
继续我们的评论。
如果您只想在脚本中嵌入 base64 打包代码块,则不应使用 powershell -EncodedCommand $encodedCommand
,因为那样只会 运行 在它自己的环境中,您的主脚本将对那里定义的函数一无所知。
为此您可以使用 Invoke-Expression
,但请务必阅读 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
结果:
ZgB1AG4AYwB0AGkAbwBuACAASABMAFMAIAB7AA0ACgAgACAAIAAgAFcAcgBpAHQAZQAtAEgAbwBzAHQAIAAnAEgAZQBsAGwAbwAsACAAVwBvAHIAbABkACEAJwANAAoAfQA=
接下来,在您的主脚本中,直接使用 $encodedCommand 的 base64 值:
$encodedCommand = 'ZgB1AG4AYwB0AGkAbwBuACAASABMAFMAIAB7AA0ACgAgACAAIAAgAFcAcgBpAHQAZQAtAEgAbwBzAHQAIAAnAEgAZQBsAGwAbwAsACAAVwBvAHIAbABkACEAJwANAAoAfQA='
Invoke-Expression ([System.Text.Encoding]::Unicode.GetString([convert]::FromBase64String($encodedCommand)))
# now the function is known and can be used
HLS
结果:
Hello, World!