网上查了powershell 加密解密的方法,有把ps脚本加密成bat的,有加密成bin的,尝试了一下,都的可以,有的不行。
我们项目中用到一个这样的脚本加密的,代码半天就写完了,加密的事情纠结了一星期,最终纠结在那个有名的加密的博客,没解释清楚如何传参进去到Invoke-Expression中,尝试了Invoke-command也没解决。
我传参的原因很简单,ps中的代码有取得当前路径的,我用到了Split-Path -parent $MyInvocation.MyCommand.Path,结果在加密后报错,不能识别这个参数。虽然最终结果用 dir .解密,仍旧是耽误了好长时间。
现把用到的加密和解密的代码列出来,
cls
function Encrypt-Script($path, $destination) {
$script = Get-Content $path | Out-String
$secure = ConvertTo-SecureString $script -asPlainText -force
$export = $secure | ConvertFrom-SecureString
Set-Content $destination $export
"Script '$path' has been encrypted as '$destination'"
}
function Execute-EncryptedScript($paths, $Param) {
trap { "Decryption failed"; break }
$raw = Get-Content $paths
$secure = ConvertTo-SecureString $raw
$helper = New-Object system.Management.Automation.