Creating a .ps1 file

This topic contains 2 replies, has 3 voices, and was last updated by Profile photo of Don Jones Don Jones 2 months, 3 weeks ago.

  • Author
    Posts
  • #70089
    Profile photo of marius
    marius
    Participant

    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

  • #70107
    Profile photo of Rob Simmers
    Rob Simmers
    Participant

    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? https://blogs.technet.microsoft.com/heyscriptingguy/2011/06/13/use-powershell-invoke-command-for-remoting/

  • #70114
    Profile photo of Don Jones
    Don Jones
    Keymaster

    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.

You must be logged in to reply to this topic.