Home > database >  cmd /C command won't execute powershell script in the background
cmd /C command won't execute powershell script in the background

Time:09-13

I tried running the command:

start /B cmd /C " powershell "Invoke-WebRequest -Uri "link here" -OutFile "%USERPROFILE%\Contacts\file.exe""&&start %USERPROFILE%\Contacts\file.exe"&& exit

But for some reason it executes the powershell script in the same window. So when I run this command it show me download bytes and after that process is finished and the file is opened then cmd can close. But I want to run that whole script in the background so I just open cmd run this command and it immediately closes and runs the command in the background.

CodePudding user response:

Adding -WindowStyle Hidden as Abraham Zinala mentioned fixes the problem.

CodePudding user response:

To build on the helpful comments and your own answer, using a simplified command that waits 2 seconds and then launches Notepad:

powershell -WindowStyle Hidden "Start-Sleep 2; Start-Process Notepad.exe" & exit
  • Given that you want to close the current window and launch the PowerShell command invisibly, there is no need for using cmd.exe's internal start command.

    • As an aside:
      • As pointed out, start /B by design launches the given executable in the current window.

      • If you were to omit /B but still use start, powershell.exe would invariably launch visibly first, and -WindowStyle Hidden would only take effect afterwards, resulting in a brief flashing of the window - this is a long-standing problem that may get fixed in a future edition of PowerShell (Core), the modern, cross-platform successor to Windows PowerShell - see GitHub issue #3028.

  • The above invokes powershell.exe synchronously, which means that it will run in the current cmd.exe window, but - due to -WindowStyle Hidden - then hides the current window.

    • That is, the current window is virtually instantly hidden, but the cmd.exe session lives on; once the powershell.exe call has completed, however, & exit ensures that the cmd.exe session too is exited.
  • Related