Send arguments to an external program in PowerShell

Paul 1 Reputation point
2021-05-23T18:57:19.607+00:00

I am having problems sending variables into the invoke-expression command below.

This launches cmd, so that PowerShell is subsequently launched in a separate Window.

invoke-expression ‘cmd /c start powershell -NoExit -Command {cd C:\Users\me\AppData\Local\app-1.1.4\resources\app.asar.unpacked\daemon\;$host.ui.RawUI.WindowTitle = $job;
start-sleep 0 ;
.\Program.exe blob make -k 32 -b 3390 -r 2 -n 1 -t $TempDisk -d $global:finaldisk -u 128 | tee C:\Users\me\Desktop\folder\Logs\Job-1.log }'

I would prefer variables for each of the command line values, but getting any at all working is a struggle :-)

Any ideas?

Many thanks
Paul

Windows for business Windows Server User experience PowerShell
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. MotoX80 36,291 Reputation points
    2021-05-23T21:43:07.753+00:00

    How about building a .ps1 script and executing it? That way you can easily see what code is being generated.

    # Here is data that comes from somewhere else. 
    $Title = "Hello There"
    $WhoamiSwitch = "/user"
    
    # Now build our script
    $Myps1 = "$env:TEMP\myscript.ps1"                  # a temporary file    
    'write-host "This is my script test"' | out-file $Myps1      # use single quote so that $ variables do not get expanded 
    'cd \' | out-file $Myps1 -Append          # note that this is the second out-file and the first with -append 
    '$host.ui.RawUI.WindowTitle = "{0}"' -f $Title | out-file $Myps1 -Append   # put the contents of the $title variable into the command to be executed 
    'whoami.exe {0}' -f $WhoamiSwitch | out-file $Myps1 -Append                # same with the whoami switch 
    '"`n----------------------------------------"' | out-file $Myps1 -Append
    '"Here is what my script contains:`n"' | out-file $Myps1 -Append
    'start-process notepad.exe  "{0}"'  -f $Myps1 | out-file $Myps1 -Append
    
    Start-Process powershell.exe -ArgumentList '-noexit', $myps1
    
    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.