3

I'm looking for a way to write a script which is able to open a new PowerShell window and to run command. E.g. I'd like to launch PowerShell, in this window I need to run a script able to open a new PowerShell window inside which the command pwd is executed.

4
  • 2
    Use the Start-Process cmdlet - on Windows, it runs the specified executable in a new window by default (on Unix, the command invariably runs in the same window). Commented Jan 24, 2021 at 23:56
  • Hello @mklement0 I tried to run the command Start-Process powershell.exe pwd, but the new PowerShell screen appears and disappears quickly. What did I do wrong? Commented Jan 25, 2021 at 8:30
  • 1
    This does the job, you forgot -NoExit Start-Process powershell -ArgumentList '-NoExit "& {pwd}"' Don't forget to check help powershell /?, Get-Help Start-Process Commented Jan 25, 2021 at 12:46
  • Also just found a good explanation of why: stackoverflow.com/questions/38831008/… Commented Jan 25, 2021 at 12:49

1 Answer 1

10

Try on of this Commands

Start-Process powershell.exe -ArgumentList "-noexit"  



 Start-Process powershell -ArgumentList "-noexit", "-noprofile", "-command &{Get-Location}"

to start the Window maximized us the Parameter -WindowStyle Maximized

Provide more Code for further Information

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

4 Comments

Plus 1 for the need for -noexit to keep the new window open (only needed if -Command / -c are also specified), but two asides:
While passing arguments as an array to -ArgumentList conceptually the best approach, it is unfortunately ill-advised due to a long-standing bug in Start-Process, still present as of this writing (v7.1) - see GitHub issue #5576. For now, using a single string comprising all arguments, enclosed in embedded "..." quoting as necessary, is the only robust approach. As discussed in the linked GitHub issue, an -ArgumentArray parameter that supports robust array-based argument passing may be introduced in the future.
Note that there's no reason to use & { ... } in order to invoke code passed to PowerShell's CLI via the -command (-c) parameter - just use ... directly. Older versions of the CLI documentation erroneously suggested that & { ... } is required, but this has since been corrected.
*Correction to the first comment: -noexit is only needed if one of the following parameters are also specified: -Command (-c), -EncodeCommand, -File.

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.