简体   繁体   English

Powershell使用Powershell命令进行编码

[英]Powershell encode with powershell commands

I have below powershell commands, 我有下面的PowerShell命令,

$tmp = Get-Content 'C:\Users\username\Documents\emp_details.txt'
$tmp[0..75], ':tech emp details', $tmp[76.. ($tmp.Count -1)] | 
    Set-Content 'C:\Users\username\Documents\emp_details.txt'

which I want to encode and this entire commands as string and store it to variable and then will decode and execute it whenever I needed. 我想将其编码,并将整个命令作为字符串存储,并将其存储到变量中,然后在需要时将其解码并执行。 But when I tried to decode using below which internally executes the Get-Content command as well. 但是,当我尝试使用以下代码进行解码时,在内部也执行Get-Content命令。

$Bytes = [System.Text.Encoding]::Unicode.GetBytes("$tmp = Get-Content 'C:\Users\username\Documents\emp_details.txt'
$tmp[0..75], ':tech emp details', $tmp[76.. ($tmp.Count -1)] | 
    Set-Content 'C:\Users\username\Documents\emp_details.txt'")
$EncodedText =[Convert]::ToBase64String($Bytes)
$EncodedText

Any idea please to encode those commands as strings without executing those commands internally. 任何想法都请在不内部执行这些命令的情况下将这些命令编码为字符串。

Phil's suggestion of making a script block is a good one. Phil提出的制作脚本块的建议是一个很好的建议。 Here is how to store the command into a variable $thecmd . 这是将命令存储到变量$thecmd

$thecmd = {$tmp = Get-Content "C:\Users\$Env:USERNAME\Documents\$emp_details.txt"
    $tmp[0..75], ':tech emp details', $tmp[76.. ($tmp.Count -1)] | 
    Set-Content "C:\Users\$Env:USERNAME\Documents\emp_details_out.txt"}

The value of $thecmd will be the scriptblock text. $thecmd的值将是$thecmd文本。 In order to run it, use the invocation operator ( & ). 为了运行它,请使用调用运算符( & )。

& $thecmd

I changed your hardcoded path to use the $Env:USERNAME variable. 我将您的硬编码路径更改为使用$ Env:USERNAME变量。 Also, what happens if the source text file does not have at least 75 lines? 另外,如果源文本文件没有至少75行,会发生什么情况?

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

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