1
votes

I have below powershell commands,

$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.

$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.

1
Look into assigning it as a script block to a variable. - Phil
On another note, the first code block appears to be reading and writing to the same file. Has this worked well? - lit

1 Answers

2
votes

Phil's suggestion of making a script block is a good one. Here is how to store the command into a variable $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. In order to run it, use the invocation operator (&).

& $thecmd

I changed your hardcoded path to use the $Env:USERNAME variable. Also, what happens if the source text file does not have at least 75 lines?