繁体   English   中英

将 PowerShell 脚本转换为不可读的格式

[英]Convert PowerShell script into non-readable format

我有一个 PowerShell 脚本,它在客户机器上安装补丁(包含要添加的文件集)。 为此,我创建了一个执行此 PowerShell 脚本的批处理文件。
要让客户运行此批处理文件,还必须将 PowerShell 脚本文件放置到客户计算机上。

PowerShell 脚本为文本格式,便于客户阅读和理解。

我们能不能把这个脚本文件转换成一些不可读的格式(比如bin或者exe),让客户无法读取?

您可以将脚本转换为 Base64 编码,这样就不能立即读取。 要将 PowerShell 脚本文件转换为 Base64 字符串,请运行以下命令:

$Base64 = [System.Convert]::ToBase64String([System.IO.File]::ReadAllBytes('c:\path\to\script file.ps1'));

要启动 Base64 编码的脚本,您可以调用 PowerShell.exe,如下所示:

powershell.exe -EncodedCommand <Base64String>

例如,以下命令:

powershell.exe -EncodedCommand VwByAGkAdABlAC0ASABvAHMAdAAgAC0ATwBiAGoAZQBjAHQAIAAiAEgAZQBsAGwAbwAsACAAdwBvAHIAbABkACEAIgA7AA==

将返回以下结果:

Hello, world!

我尝试了@TrevorSullivan 提出的解决方案,但它给了我错误

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

后来我发现编码有问题。 我找到了另一种方法,当我将这两者结合起来时,我得到了有效的 PS 命令:

$Base64 = [System.Convert]::ToBase64String([System.Text.Encoding]::Unicode.GetBytes([System.IO.File]::ReadAllText("script.ps1")))

然后我可以将结果重定向到文件:

$Base64 > base64Script.txt

从那里我只是复制编码的命令并将其粘贴在这里而不是<Base64String>

powershell.exe -EncodedCommand <Base64String>

它可以毫无问题地工作。

谢谢你们的帖子。 我接受了@Frimlik 的帖子并创建了自己的脚本来自动化该过程。 我希望这可以帮助别人。 将脚本保存到 ps1 文件并运行它。

Function Get-FileName($initialDirectory)
{
    [System.Reflection.Assembly]::LoadWithPartialName("System.windows.forms") | Out-Null    
    $OpenFileDialog = New-Object System.Windows.Forms.OpenFileDialog
    $OpenFileDialog.initialDirectory = $initialDirectory
    $OpenFileDialog.ShowDialog() | Out-Null
    $OpenFileDialog.filename
}

Function EncodePS1ToBat {
    $ScriptToEncode = Get-FileName
    # Encode the script into the variable $Base64
    $Base64 = [System.Convert]::ToBase64String([System.Text.Encoding]::Unicode.GetBytes([System.IO.File]::ReadAllText($ScriptToEncode)))

    # Get the path and name to be used as output
    $filePath = Split-Path $ScriptToEncode -Parent
    $fileName = (Split-Path $ScriptToEncode -Leaf).Split(".")[0]

    # Output the encoded script into a batch file on the same directory of the origial script
    "@echo off`n powershell.exe -ExecutionPolicy Bypass -EncodedCommand  $Base64"  | 
    Out-File -FilePath "$filePath\$fileName`_Encoded.bat" -Force -Encoding ascii
}
# Call the funtion to encode the script to a batch file
EncodePS1ToBat

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM