[英]Powershell script with embedded exe
有没有办法将 exe 嵌入到现有的 powershell 脚本中? 我的老板希望我想出一种方法,在我们的员工计算机上安装软件,这些计算机在家工作并且不精通技术。 本质上,我需要将一个文件本地复制到他们的计算机(这是一个 exe)并从 powershell(或命令行)终端使用一些 arguments(即 /norestart /quiet 等)运行它。
您可以使用 Base64 编码将 exe嵌入到 PowerShell 脚本中。 运行此脚本对 exe 进行编码。 它在下载文件夹中生成“base64Decoder.ps1”。
# Requires PowerShell 5.1
# Run this script to encode the exe.
# It produces 'base64Decoder.ps1' in the Downloads folder.
$folder = "$env:UserProfile\Downloads\Demo\"
$file = "PowerShell-7.0.0-win-x64.msi"
$option = [System.Base64FormattingOptions]::InsertLineBreaks
$path = Join-Path -Path $folder -ChildPath $file
$bytes = Get-Content $path -Encoding Byte -ReadCount 0
$outputProgram = [System.Text.StringBuilder]::new()
[void]$outputProgram.AppendLine( '$encodedText = @"' )
[void]$outputProgram.AppendLine( ([Convert]::ToBase64String($bytes, $option)) )
[void]$outputProgram.AppendLine( '"@' )
[void]$outputProgram.Append(
@"
`$downloads = Join-Path -Path `$Env:USERPROFILE -ChildPath "Downloads"
`$file = "$file"
`$path = Join-Path -Path `$downloads -ChildPath `$file
`$value = [System.Convert]::FromBase64String(`$encodedText)
Set-Content -Path `$path -Value `$value -Encoding Byte
"@
)
$downloads = Join-Path -Path $Env:USERPROFILE -ChildPath "Downloads"
$outFile = "base64Decoder.ps1"
$outPath = Join-Path -Path $downloads -ChildPath $outFile
Set-Content -Path $outPath -Value ($outputProgram.ToString())
您可以将base64Decoder.ps1的内容复制并粘贴到现有的 PowerShell 脚本中以嵌入 exe。 或者,如果太大,请将 base64Decoder.ps1 包含在原始脚本中,并在必要时调用它。
在目标计算机上运行脚本以重现下载文件夹中的原始文件。 这是有效的 PowerShell 语法,可以包含在脚本中。
& "$env:UserProfile\Downloads\base64Decoder.ps1"
您可能必须在脚本运行之前设置执行策略。
Set-ExecutionPolicy RemoteSigned
使用Start-Process调用 exe。 这可以保存在脚本中。
Start-Process -FilePath "$env:UserProfile\Downloads\PowerShell-7.0.0-win-x64.msi" -ArgumentList '/? '
如果您想通过电子邮件发送 PowerShell 脚本,请将其附加为 .txt 并让他们重命名。 我确定您知道文件附件通常限制为 10MB。
如果 exe 可以在线获得,您可以使用更简单的 Invoke-WebRequest 。
Invoke-WebRequest "https://github.com/PowerShell/PowerShell/releases/download/v7.0.0/PowerShell-7.0.0-win-x64.msi" -outfile "$env:UserProfile\Downloads\PowerShell-7.0.0-win-x64.msi"
您可以在Windows Sandbox中测试这些步骤。
虽然这是您问题的技术正确答案,但我不推荐它。
首先,它比简单地从 Internet 下载安装程序并使用( MSI )打开它更复杂。
其次,我的脚本的性能对于非平凡的 exe 来说很差。 而且它会产生比它解决的更多的问题。
我不确定这里的假设是什么。 但如果这些计算机不受管理,我想每次安装都会有一个支持请求。 您将无法做的只是将此脚本通过电子邮件发送给 100 个人,或者将其放入登录脚本中然后走开。 那将是非常糟糕的。 即使这是在办公室,我也不会在没有彻底测试的情况下部署无人值守的安装。 这是假设本地存储和登录脚本或等效的:不是一次性在家工作的人。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.