Creating a .ps1 file

I need to create a simple .ps1 file on a target machine and run it.
The .ps1 file I need to create is quite simple and looks like:

param($my_exe) 
$CMD = $my_exe
$CMD >> c:\logs\exe_name.log
& $CMD

At the moment I copy my file but I’d prefer to create it on the target machine.
I created a script to create the target script but there is something wrong.
My script looks like:

$line1 = "param($my_exe)"
$line2 = "$CMD = $my_exe"
$line3 = "$CMD >> c:\logs\exe_name.log"
$line4 = "& $CMD"
$target = "C:\myfiles\myscript.ps1"
$line1 > $target 
$line2 >> $target 
$line3 >> $target 
$line4 >> $target 

I have two troubles:

  • When I say
$line1 > $target 
how can I ensure that the task was executed successfully?
  • As my script contains special characters and words that can be interpreted as avariables,
$line2 = "$CMD = $my_exe"
$line2 >> $target 

how can I ensure that they are written as expected?
Regards
marius

It appears you are trying to run a command on remote machine. Is there a reason you are not using Invoke-Command or other powershell remoting solutions? Use PowerShell Invoke-Command for Remoting - Scripting Blog

Well… OK, you’re taking a very Cmd.exe approach, which isn’t the best for PowerShell. First, some things to look up:

Try using a here-string instead of this half-dozen “line” variables. Get all your text in one variable.

Use Out-File instead of the angle brackets. Output all the text in one command.

Use single quotes to stop the shell from treating anything as a special variable.