Powershell使用powershell命令进行编码

时间:2017-05-06 14:58:39

标签: powershell

我有以下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'

我想编码并将整个命令作为字符串并将其存储到变量中,然后在需要时解码并执行它。但是当我尝试使用下面的解码时,内部也会执行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

任何想法请将这些命令编码为字符串而不在内部执行这些命令。

1 个答案:

答案 0 :(得分:2)

菲尔建议制作一个脚本块是一个很好的建议。以下是将命令存储到变量$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"}

$thecmd的值将是scriptblock文本。要运行它,请使用调用运算符(&)。

& $thecmd

我更改了您的硬编码路径以使用$ Env:USERNAME变量。另外,如果源文本文件没有至少75行,会发生什么?