Creating a .ps1 file

Welcome Forums General PowerShell Q&A Creating a .ps1 file

This topic contains 2 replies, has 3 voices, and was last updated by

1 year, 9 months ago.

  • Author
  • #70089

    Points: 1
    Rank: Member

    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:

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

  • #70107

    Points: 492
    Helping Hand
    Rank: Contributor

    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?

  • #70114

    Points: 1,811
    Helping HandTeam Member
    Rank: Community Hero

    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.

The topic ‘Creating a .ps1 file’ is closed to new replies.

denizli escort samsun escort muğla escort ataşehir escort kuşadası escort