[英]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.