0

I'm writing a Powershell script that takes in a text file as a parameter. The text file looks similar to this:

echo "1"
echo "2"
echo "3"

What I would want is for each line to be executed in a new Powershell instance. So in the example above, 3 additional instances would be created and each of the 3 would execute one line from the text file. I'm able to launch instances, but I cannot get the instances to treat the lines in the file as commands.

$textFile=$args[0] #File with Powershell commands

foreach($cmdd in get-content $textFile){
    cmd /c start powershell -NoExit -command {param($cmdd) iex $cmdd} -ArgumentList $cmdd
}

Running this code opens the instances, prints a lot of information, and then immediately closes. It closes so quickly that I cannot see what the info is. However, since the text file is only composed of printing the numbers 1, 2, and 3, I don't think that it's working correctly. Is there also a way to keep the windows from closing after execution?

2 Answers 2

1

If you're launching additional instances of PowerShell from PowerShell, you won't need to call cmd. Try using Start-Process:

$textFile=$args[0] #File with Powershell commands

foreach($cmdd in get-content $textFile){
    Start-Process -FilePath powershell -ArgumentList "-NoExit -Command $cmdd"
}

This will leave newly created instances open as you have asked.

Sign up to request clarification or add additional context in comments.

Comments

0

Switch from CMD /C to CMD /K to leave the command session open after the command finishes.

2 Comments

The newly created instances still close. I want to keep those open too.
If you want to launch instances outside of the current session, you'll need to use Start-Process. But I don't think you can use a scriptblock for your command argument in that context.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.