网上查了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.PSCredential("test", $secure)
$plain = $helper.GetNetworkCredential().Password
$cc='$Curent='+"$Param"
$ss="$cc $plain"
#Invoke-Expression '$plain | Where-Object {$_.Curent $Param}'
# Invoke-Expression $ss
Invoke-Expression $plain
#Invoke-Command -Curent $Param -ScriptBlock {$plain}
#Invoke-Command -ScriptBlock {$ss} #-ArgumentList $Param
}
$Pa="D:\RPA_Project\Project\"
Encrypt-Script $Pa\MergePicture.ps1 $Pa\CombinPic.bin
Execute-EncryptedScript $Pa\CombinPic.bin -Param $Pa
本文介绍了在项目中遇到的PowerShell脚本加密和解密的问题,特别是关于参数传递的困扰。作者分享了用于加密和解密的自定义函数,并详细描述了解决Split-Path命令在加密后无法识别的问题。最终,提供了成功执行加密脚本的解决方案。
1357

被折叠的 条评论
为什么被折叠?



