james
james

Reputation: 354

How to create a new window and set UseShellExecute false in powershell?

The requirement is a bit strange, I've encountered a strange stuck problem in multi-thread in powershell. So I want to create a new window and don't use shell Execute. But I cannot make it with below code, the window doesn't show up. $approot is desktop, in start.bat, just do "dir /s .\" I want the dir result shows in another window instead of the window execute this script, and I don't want use shell execute.

$startInfo = New-Object system.Diagnostics.ProcessStartInfo
$startInfo.UseShellExecute = $false
$startinfo.FileName = $env:ComSpec
$startInfo.CreateNoWindow = $false
$startInfo.Arguments = "/c cd /d $AppRoot & call start.bat"
$process = New-Object System.Diagnostics.Process
$process.StartInfo = $startInfo
$process.Start() | Out-Null

Upvotes: 1

Views: 2929

Answers (1)

mklement0
mklement0

Reputation: 440297

If you set .UseShellExecute to $False, you cannot start your command in a new console window (the only thing you can do in that case is to run a console-based command hidden, by setting .CreateNoWindow to $true; at its default, $false, the command runs in the caller's console window).

Therefore, you may as well use Start-Process, which leaves .UseShellExecute at its default, $True[1].

Start-Process $env:ComSpec -Args '/k', "cd /d `"$AppRoot`" & call start.bat"

To promote good habits, $AppRoot is enclosed in embedded double quotes (escaped as `") to properly deal with paths containing spaces. While this is not strictly necessary with cmd.exe's cd, it is with virtually all other commands / programs.

Note that I'm using /k rather than /c as the cmd.exe ($env:ComSpec) switch to ensure that the new windows stays open.


If setting .UseShellExecute to $False is a must, use conhost.exe to explicitly create a new window (requires Windows 10):

$process = New-Object System.Diagnostics.Process
$process.startInfo.UseShellExecute = $false
$process.startinfo.FileName = 'conhost.exe'
$process.startInfo.Arguments = "cmd /k cd /d `"$AppRoot`" & call start.bat"
$null = $process.Start()

On other flavors / versions of Windows, you may be able to use P/Invoke to call the CreateProcess() Windows API function directly, using the CREATE_NEW_CONSOLE flag.


[1]

  • Note that certain Start-Process parameters, such as -NoNewWindow and -Credential, require that .UseShellExecute be set to $False, in which case the CreateProcess() WinAPI function is used (rather than ShellExecute()) behind the scenes.
  • Also note that in .NET Core .UseShellExecute's default is now $False, but PowerShell Core's Start-Process still defaults to $True to match Windows PowerShell's behavior.

Upvotes: 2

Related Questions